本題要求實現一個函數,用下列公式求cos(x)近似值,精確到最后一項的絕對值小於eps(絕對值小於eps的項不要加):
cos (x) = x^0 / 0! - x^2 / 2! + x^4 / 4! - x^6 / 6! + ?
函數接口定義:funcos(eps,x ),其中用戶傳入的參數為eps和x;函數funcos應返回用給定公式計算出來,保留小數4位。
函數接口定義:
函數接口: funcos(eps,x ),返回cos(x)的值。
裁判測試程序樣例:
在這里給出函數被調用進行測試的例子。例如: /* 請在這里填寫答案 */ eps=float(input()) x=float(input()) value=funcos(eps,x ) print("cos({0}) = {1:.4f}".format(x,value))
輸入樣例:
在這里給出一組輸入。例如:
0.0001 -3.1
輸出樣例:
在這里給出相應的輸出。例如:
cos(-3.1) = -0.9991
1 # 使用函數求余弦函數的近似值
2 # Author: cnRick
3 # Time : 2020-4-12
4 import math 5 def getFactor(x): 6 if x == 0: 7 return 1
8 else: 9 return x*getFactor(x-1) 10 def funcos(eps,x): 11 breakFlag = False 12 cosx = 0 13 fenmu = 0 14 flag = 1
15 while True: 16 this = flag*math.pow(x,fenmu)/getFactor(fenmu) 17 if abs(this) < eps: 18 return cosx 19 cosx = cosx + this 20 fenmu += 2
21 flag = -flag