Python:如何解决基本“混沌理论”程序中的舍入错误?

2024-05-19 10:54:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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这样的输出值?这样的问题怎么处理?你知道吗


Tags: and程序numbermaindefevalfunctionbetween
1条回答
网友
1楼 · 发布于 2024-05-19 10:54:04

问题来自您正在使用的中间步骤:eval调用(这并不是将用户输入解析为float的最佳方法,float函数更安全)。这会将用户的输入计算到Python解释器本机将其解析为的任何内容中,在本例中这将是一个float。这意味着,当您执行Decimal(eval(input()))操作时,在将数据传递给Decimal之前,您已经对数据进行了干扰,而Decimal只对给定的数据起作用。删除eval调用,让Decimal本身处理用户的输入。此外,您还必须清除其他所有本机浮点值,例如Decimal(3.9),它首先从3.9中创建一个浮点值,然后再从中创建Decimal。可以通过将字符串传递给Decimal来避免这种情况。你知道吗

>>> Decimal(Decimal(3.9) * Decimal(eval('.15')) * (Decimal(1) - Decimal(eval('.15'))))
Decimal('0.4972499999999999735211808627')
>>> Decimal(Decimal(3.9) * Decimal(.15) * (Decimal(1) - Decimal(.15)))
Decimal('0.4972499999999999735211808627')
>>> Decimal(Decimal(3.9) * Decimal('.15') * (Decimal(1) - Decimal('.15')))
Decimal('0.4972499999999999886757251488')
>>> Decimal(Decimal('3.9') * Decimal('.15') * (Decimal('1') - Decimal('.15')))
Decimal('0.49725')

相关问题 更多 >

    热门问题