代码之家  ›  专栏  ›  技术社区  ›  Dessie

如何提高此python代码中的计算精度

  •  1
  • Dessie  · 技术社区  · 2 年前

    我正试图重现《小数学快报》第81页上的一个情节(顺便说一句,这是一本很有趣的数学书)。该图是使用一对迭代应用的简单函数创建的(即,每个循环的输出是下一个循环的输入)。在每个循环中绘制输出x,y点应该会产生一个美丽的复杂点云。然而,当我实现下面的代码时,在第五十次迭代后,它会在4个相同的点之间循环。我认为这是由于我的变量定义精度不够而导致的四舍五入。我该如何改进?

    import matplotlib.pyplot as plt
    
    x = 0
    y = 0
    vecx = []
    vecy = []
    
    for i in range(5000):
        x = 1.3 + 0.3*x + 0.6*x*y - 0.6*y - y**2
        y = 0.1 - 0.7*x + 0.5*(x**2) - 0.8*x*y + 0.1*y - 0.6*(y**2)
        vecx.append(x)
        vecy.append(y)
        
    plt.plot(vecx, vecy, 'b.')
    
    3 回复  |  直到 2 年前
        1
  •  3
  •   Navkar Jain    2 年前

    我尝试了100次迭代,并且工作正常:

    x = 0
    y = 0
    vecx = []
    vecy = []
    
    for i in range(100):
        new_x = 1.3 + 0.3*x + 0.6*x*y - 0.6*y - y**2
        new_y = 0.1 - 0.7*x + 0.5*(x**2) - 0.8*x*y + 0.1*y - 0.6*(y**2)
        
        x, y = new_x, new_y  # Update x and y for the next iteration        
    
        vecx.append(x)
        vecy.append(y)
    
        print('x', x)
        print('y', y)
    
        
    
        2
  •  1
  •   chubercik    2 年前

    您可以使用 decimal Python模块:

    from decimal import Decimal, getcontext
    
    # Set the precision for decimal calculations
    getcontext().prec = 50  # You can adjust the precision as needed
    
    x = Decimal('0')
    y = Decimal('0')
    vecx = []
    vecy = []
    
    for i in range(5000):
        x_new = Decimal('1.3') + Decimal('0.3') * x + Decimal('0.6') * x * y - Decimal('0.6') * y - y**2
        y_new = Decimal('0.1') - Decimal('0.7') * x + Decimal('0.5') * (x**2) - Decimal('0.8') * x * y + Decimal('0.1') * y - Decimal('0.6') * (y**2)
        x, y = x_new, y_new
        vecx.append(x)
        vecy.append(y)
    
        3
  •  -1
  •   dawid.pawlowski    2 年前

    您应该尝试使用十进制库进行精确的浮点数字计算。 from decimal import Decimal 并以字符串形式提供数字 y = Decimal('1.005')