I\'m trying to write some code that\'ll calculate the value of sin(0.75) using the Taylor expansion, and print each iteration until the absolute difference between the value cal
It looks too obvious to most people so no-one even wanted to answer, but it should be said explicitly
The condition x - sin(0.75) < 10**(-6)
is obviously not true when x
very different from sin(0.75)
, so the do while
loop is never entered.
Also, as IanH commented 10**(-6)
will give 0 because the result of the power of two integers is again an integer. The literal real
number 10^-6 should be expressed as 1e-6
.
If you change it to x - sin(0.75) > 1e-6
the loop will proceed, but it will run forever, because your iteration is wrong. Taylor series works differently, you should compute
y = 0
y = y + x**1/1!
y = y - x**3/3!
y = y + x**5/5!
y = y - x**7/7!
...
and so on, which is a very different kind of loop.
Try this one:
program taylor
implicit none
real :: x = 0.75
real :: y, fact
integer :: sgn, i
fact = 1
sgn = 1
y = 0
do i = 1, 10, 2
y = y + sgn * x**i / fact
fact = fact*(i+1)*(i+2)
sgn = -sgn
end do
print *, y, sin(x)
end program taylor