I want to compare the value of sum of Taylor series with intrinsic function in Fortran 95. However, the answer for Taylor series is wrong. Below is the code I wrote
program taylor_sin
implicit none
integer, parameter :: dp = selected_real_kind(15, 307)
integer :: i
real(dp) :: x_rad , term, sum, fact, y, delta
write(*,*) "Enter the value of x in degree:"
read(*,*) y
x_rad = y * (3.14159265358979323846 / 180.0)
! Initialize the sum and the factorial
sum = 0.0_dp
fact = 1.0_dp
delta = 10.0E-8
! Calculate the Taylor series expansion
do
i = 1
term = ((-1)**i) * (x_rad**(2*i + 1)) / fact
fact = fact*(2*i + 1)
sum = sum + term
if( (sum - sin(y) ) < delta)exit
end do
! Print the result
write(*,*) " from the Taylor series"
write(*,*) "sin(", y, ") = ", sum
! Print the result
write(*,*) "intrinsic value for sin x", sin(y)
end program taylor_sin
I expect the value for both Taylor and intrinsic to be near similar
With sin(x), you should exploit the fact that you have an odd function and it is periodic. That is sin(-x) = -sin(x) and you can fold the argument into the range 0 <= x <= 360. As @lastchance indicates, you probably want to recursively compute the next term in the series instead of explicitly computing the factorial and the value of x raised to some integer value. Here's how I would do it with only very limited testing.