python使用函数求余弦函数的近似值

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

cos(x)=x0​/0!−x2/2!​+x4/4!​−x6​/6!+...

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

函数接口定义:

函数接口:
funcos(eps,x),返回cos(x)的值。

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:


/* 请在这里填写答案 */

eps,x = input().split()
value = funcos(float(eps),float(x))
print("cos({0}) = {1:.4f}".format(float(x),value))

输入样例:

0.0001  -3.1

输出样例:

cos(-3.1) = -0.9991

代码示例:

def funcos (eps,x):
    #正负号
    PositiveOrNegative = 1
    #计数器
    Cou = 0
    #近似值
    cosX = 0
    while(True):
        temp = PositiveOrNegative * pow(x,Cou) / math.factorial(Cou)
        #精确到最后一项的绝对值小于eps
        if abs(temp) < eps:
            return cosX
        cosX += temp
        #正负号变化
        PositiveOrNegative *= -1
        Cou += 2
eps,x = input().split()
value = funcos(float(eps),float(x))
print("cos({0}) = {1:.4f}".format(float(x),value))

以上代码全为本人亲自手敲,可能有一些错误和不足之处,如有更好的方法和建议,欢迎您在评论区友善讨论。 

你可能感兴趣的:(python,python)