from math import fabs
from math import pi
def sin(x):
g = 0
t = x
n = 1
while (fabs(t) >= 1e-10):
g += t
n += 1
t = -t * x * x / (2 * n - 1) / (2 * n - 2)
return g
ans = sin(pi / 2)
print(ans)
0.9999999999939768
- 初始:
g = 0, n = 2 , t = x
t = x 1 ! t=\frac{x}{1!} t=1!x
进入循环
- 第一步:
g = x, n=2, t = -x*x*x / 3 /2
也就是
g = x 1 ! , t = − x 3 3 ! g=\frac{x}{1!}, t=-\frac{x^3}{3!} g=1!x,t=−3!x3
- 第二步:
g = x - xxx/6
n = 3
t = -(-x*x*x/3/2)*x*x / 5 / 4
g = x 1 ! − x 3 3 ! , t = x 5 5 ! g=\frac{x}{1!} -\frac{x^3}{3!}, t=\frac{x^5}{5!} g=1!x−3!x3,t=5!x5
以此类推,也就是sinx
的公式
s i n x = x 1 ! − x 3 3 ! + x 5 5 ! − x 7 7 ! + . . . = ∑ n = 1 ∞ ( − 1 ) n − 1 x 2 n − 1 ( 2 n − 1 ) ! sinx=\frac{x}{1!} -\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+...=\sum_{n=1}^{\infty}(-1)^{n-1}\frac{x^{2n-1}}{(2n-1)!} sinx=1!x−3!x3+5!x5−7!x7+...=n=1∑∞(−1)n−1(2n−1)!x2n−1
参考:
《C++语言程序设计》 郑莉等,例3-5.