6-2 使用函数求余弦函数的近似值

 

本题要求实现一个函数,用下列公式求cos(x)近似值,精确到最后一项的绝对值小于eps(绝对值小于eps的项不要加):

cos(x)=0!x02!x2+4!x46!x6+...

函数接口定义:funcos(eps,x),其中用户传入的参数为eps和x;函数funcos应返回用给定公式计算出来,保留小数4位。

 1 def factorial(n):
 2     if n==0:
 3         return 1
 4     sum=n*factorial(n-1)
 5     return sum
 6 
 7 def funcos(eps,x):
 8     s=0
 9     j=0
10     while 1 == 1:
11      num = x**j/factorial(j)
12      if num < eps:
13          return s
14      if j%4==0:
15          s=s+num
16      else:
17          s=s-num
18      j = j+2

 

posted @ 2023-03-07 15:11  旺旺大菠萝  阅读(58)  评论(0编辑  收藏  举报