Program For Calculating Sin Using Taylor Expansion Not Working?

后端 未结 1 1315
萌比男神i
萌比男神i 2021-01-27 11:45

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

相关标签:
1条回答
  • 2021-01-27 12:14

    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
    
    0 讨论(0)
提交回复
热议问题