0

I have code that is supposed to return a table with values that solve a particular system of equations using Backwards Euler Method.

I wrote code for one a timestep of 0.025, and it has returned me the necessary values, however, when I increase the amount of calculations, at some point the accuracy is lost because of lack of decimal spaces at the end of the values. It just returns the same numbers over and over. What can I do to increase accuracy? I have tried working with decimal but it still returns me the same values, some with less accuracy

This is the code that works:

delta3 = float(0.025)
nfinal3 = 1/0.025
ic3 = numpy.array([[1], [1]]) 
be3 = PrettyTable(['t','x','y'])
for l in range(0, int(nfinal3)):
    x3=ic3[0] 
    y3=ic3[1]
    firstline3 = -199*(x3+delta3)-198*(y3+delta3)
    secondline3 = 99*(x3+delta3)+98*(y3+delta3)
    systems3 = numpy.array([[firstline3], 
                       [secondline3]]) 
    step3 = delta3*systems3
    result3 = numpy.array([[ic3[0] + step3[0]], [[ic3[1]+step3[1]]]])
    ic3[0]=result3[0]
    ic3[1]=result3[1]
    be3.add_row([l+1, result3[0], result3[1]])
print be3[0]

and this is the code that gives inaccurate numbers

t4 = 0.01
n4 = 1/t4
ic4 = numpy.array([[1],[1]])
be4 = PrettyTable(['t','x','y'])
for q in range(0, int(n4)):
    x4=ic4[0]
    y4=ic4[1]
    firstline4 = t4*(-199*(x4+t4)-198*(y4+t4))
    secondline4 = t4*(99*(x4+t4)+98*(y4+t4))
    result4 = numpy.array([[ic4[0]+firstline4], [ic4[1]+secondline4]])
    ic4[0]=result4[0]
    ic4[1]=result4[1]
    be4.add_row([q+1, result4[0], result4[1]])
print be4

I'm relatively new to Python, so I might not understand higher-end concepts, but I would appreciate if anyone could point out what I'm doing wrong or what is a good module or function to use for this.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
PikaTaco
  • 3
  • 1

2 Answers2

0

Welcome to StackOverflow!

For higher accuracy, you could use decimal module in python. Simply wrap your decimal number with Decimal function (e.g. Decimal(0.025)) instead of float. There are operations function in the documentation that you could explore too. Use that in priority to the usual operation functions.

Andreas
  • 2,455
  • 10
  • 21
  • 24
0

You could make your numpy arrays to store 128-bit floating points like so: result4 = np.array([[ic4[0]+firstline4], [ic4[1]+secondline4]], dtype = np.float128). You will have to do this for all the numpy arrays being used in the calculation. You can also make your scalars to be 0-Dimensional Numpy arrays with 128-bit like so t4 = np.array(0.01, dtype=np.float128). Then you'll need to re-write your operations using only Numpy arrays. Another alternative is to use the decimal library from https://docs.python.org/2/library/decimal.html

Piyush Singh
  • 2,736
  • 10
  • 26
  • Thank you! My system could not handle 128-bit points, but it worked with 64-bit points, which fixed my problem. – PikaTaco Nov 12 '18 at 14:33