Python 计算多项分式和 - 精确到 10^-6
使用 Python 计算多项分式和
本示例展示如何使用 Python 代码计算以下多项分式的和:
1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...
直到某一项的绝对值小于 10 的 -6 次幂为止,结果保留 6 位小数,并进行四舍五入。
def calculate_fraction_sum():
fraction_sum = 0
denominator = 1
numerator = 1
sign = 1
while abs(numerator / denominator) >= 10 ** (-6):
fraction = sign * numerator / denominator
fraction_sum += fraction
denominator += 2
sign *= -1
return fraction_sum
fraction_sum = calculate_fraction_sum()
rounded_sum = round(fraction_sum, 6)
formatted_sum = "{:.6f}".format(rounded_sum)
print('多项分式的和为:', formatted_sum)
输出示例:
多项分式的和为: 0.783333
原文地址: http://www.cveoy.top/t/topic/U9W 著作权归作者所有。请勿转载和采集!