为什么答案不同?

问题描述 投票:0回答:1

我有求欧拉数这段代码的答案:

import math 

Sn = 0

x = 1

big_n = 10000

for i in range(0,big_n,1):
    Sn = Sn + ((x**i)/(math.factorial(i)))

print(Sn)
print(math.e)

输出:

2.7182818284590455 2.718281828459045

问题:

为什么第一个输出比第二个输出多一位数?

我尝试回答,这是因为数学。e 长度恒定,但老师说不是

python python-3.x math logic eulers-number
1个回答
0
投票

是的,你是对的,math.e是数学库中的常数值(固定值和长度),浮点数存储在16位中,其余超过16位的数字/值都是垃圾值,因此我们必须对输出进行操作

由于 math.e 是一个常量,因此不建议操纵它的值(即使你仍然想操纵它,这将是一个更长且复杂的事情)....

你已经从第一个数字中删除了多余的小数

import math 
Sn = 0
x = 1
big_n = 10000
for i in range(0,big_n,1):
    Sn = Sn + ((x**i)/(math.factorial(i)))

if len(str(Sn).split(".")[1])>15:
    Sn=float(str(Sn)[:-1])#converts 'Sn' to string and removes the last character and then converts 'Sn' back to float if and only if the number of digits after space is greater than 15

print(Sn)
print(math.e)

这将为您提供相同位数的答案

© www.soinside.com 2019 - 2024. All rights reserved.