python实现sin函数

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
  1. 初始:
    g = 0, n = 2 , t = x
    t = x 1 ! t=\frac{x}{1!}
    进入循环
    1. 第一步:
      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!}
    2. 第二步:
      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!}
      以此类推,也就是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)!}

参考:
《C++语言程序设计》 郑莉等,例3-5.

猜你喜欢

转载自blog.csdn.net/m0_37586991/article/details/89815490