Python 函数计算级数部分和:x - x^3/3! + x^5/5! - ...
def series_sum(x, n):
'Computes the sum of the series s=x-x^3/3!+x^5/5!-x^7/7!+...
up to n terms for a given value of x
Args:
x (float): the value of x
n (int): the number of terms in the series to sum
Returns:
sum (float): the sum of the series up to n terms
'
sum = 0
sign = 1
factorial = 1
for i in range(1, 2*n+1, 2):
sum += sign * (x**i / factorial)
sign *= -1
factorial *= (i+1) * (i+2)
return sum
# example usage
x = 2
n = 5
print(series_sum(x, n)) # should output 1.1472222222222223
原文地址: https://www.cveoy.top/t/topic/mWAR 著作权归作者所有。请勿转载和采集!