Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I increase the precision of the calculations in this python code

I am trying to reproduce a plot on page 81 of Math Letters Jr. (which is a great recreational math book, by the way). The plot is created using a pair of simple functions that are applied iteratively (i.e. the output of each loop is the input for the following loop). Plotting the output x, y point in each loop should produce a beautiful complex point cloud. However, when I implemented the code below, it gets stuck cycling between 4 identical points after the fiftieth iteration. I assume this is due to rounding due to insufficient precision in my variable definitions. How can I improve on this?

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.')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One thing you can do is use the decimal module of 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading