使用泰勒展开计算罪的程序不工作? [英] Program For Calculating Sin Using Taylor Expansion Not Working?
问题描述
我试图编写一些代码,使用泰勒展开式计算sin(0.75)的值,并打印每个迭代,直到使用展开式计算出的值与使用Fortran内部式计算出的值之间的绝对差值sin函数小于1E-6。这是我的代码:
程序taylor
隐式无
真:: x = 0.75 $ b $ (x-sin(0.75)<10 **( - 6))
print *,x
x = x - ((x ** 3)/ 6)+((x * * 5)/ 120) - ((x ** 7)/ 5040)
end do
end program taylor
然而,这不会打印出任何东西吗?为什么会这样?
对于大多数人来说,这看起来太明显了,所以没有人甚至想回答,但应该说明确地
条件 x - sin(0.75)<当
x
非常不同于 sin(0.75)$ c时,10 **( - 6)
$ c $>,所以不会进入。
另外,IanH评论 10 **( - 6)
会给0,因为两个整数的幂的结果又是一个整数。文字 real
数字10 ^ -6应该表示为 1e-6
。
如果将其更改为 x - sin(0.75)> 1e-6
循环将继续,但它会永远运行,因为你的迭代是错误的。泰勒系列的工作方式不同,你应该计算
y = 0
y = y + x ** 1/1!
y = y - x ** 3/3!
y = y + x ** 5/5!
y = y - x ** 7/7!
...
等等,这是一种非常不同的循环。 / p>
试试这个:
程序taylor
隐含无
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)
结束程序taylor
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 calculated using the expansion, and the value calculated using Fortran's intrinsic sin function is less than 1E-6. Here is my code:
program taylor
implicit none
real :: x = 0.75
do while (x - sin(0.75) < 10**(-6))
print *, x
x = x - ((x**3)/6) + ((x**5)/120) - ((x**7)/5040)
end do
end program taylor
However, this doesn't print anything out? Why is this?
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
这篇关于使用泰勒展开计算罪的程序不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!