我从Zelle对Python的介绍中学习了Python,并遇到了下面一个基于初始输入模拟混沌输出的basic程序示例。你知道吗
def main():
print("This program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(10):
x = 3.9 * x * (1 - x)
print(x)
main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .15
0.49724999999999997
0.97497050625
0.09517177095121285
0.3358450093643686
0.8699072422927216
0.4413576651876355
0.9615881986142427
0.14405170611022783
0.48087316710014555
0.9735732406265619
我知道,对于Python中默认的双精度浮点数据类型,这种舍入错误是不可避免的。例如,第一个输出值正好是0.49725。我从某处读到,舍入错误可以通过使用Python的Decimal库中的Decimal函数来解决。所以我稍微修改了程序:
from decimal import Decimal
def main():
print("This program illustrates a chaotic function")
x = Decimal(eval(input("Enter a number between 0 and 1: ")))
for i in range(10):
x = Decimal(Decimal(3.9) * x * (Decimal(1) - x))
print(x)
main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .15
0.4972499999999999735211808627
0.9749705062499999772282405220
0.09517177095121305485295678083
0.3358450093643692781451067085
0.8699072422927223412528927684
0.4413576651876335014022344487
0.9615881986142417803060044330
0.1440517061102311988874201782
0.4808731671001548246798042829
0.9735732406265634386141115723
有没有办法解决这个问题,以便精确地表示0.49725这样的输出值?这样的问题怎么处理?你知道吗
问题来自您正在使用的中间步骤:
eval
调用(这并不是将用户输入解析为float的最佳方法,float
函数更安全)。这会将用户的输入计算到Python解释器本机将其解析为的任何内容中,在本例中这将是一个float。这意味着,当您执行Decimal(eval(input()))
操作时,在将数据传递给Decimal
之前,您已经对数据进行了干扰,而Decimal
只对给定的数据起作用。删除eval
调用,让Decimal
本身处理用户的输入。此外,您还必须清除其他所有本机浮点值,例如Decimal(3.9)
,它首先从3.9中创建一个浮点值,然后再从中创建Decimal
。可以通过将字符串传递给Decimal
来避免这种情况。你知道吗相关问题 更多 >
编程相关推荐