Skip to content Skip to sidebar Skip to footer

Matplotlib Plot Shows An Unnecessary Diagonal Line

So I'm trying to plot the approximation of an equation using Euler's method, and it works, the only problem is that the plot shows a diagonal line from the first point to the last,

Solution 1:

The problem occurs because you are using mutable type as default parameter (([],[])). What happens is every new function Teuler call reuses the same arrays. You can see it by adding print statement at the beginning of the Teuler:

print('arr length: ', len(arr[0]), len(arr[0]))

After calling it:

t1=Teuler(0, 1, 0.1, 0.16524,0.1,240)
t01 = Teuler(0, 1, 0.1, 0.16524,0.1,240)
t001=Teuler(0, 1, 0.1, 0.16524,0.01,240)
t0005= Teuler(0, 1, 0.1, 0.16524,0.0005,240)
arr length:  0 0
arr length:  2400 2400
arr length:  4800 4800
arr length:  28800 28800

So, your t... arrays start from beginning multiple times, that's what the diagonal lines give evidence of. What you need to do is whether pass mutable classes explicitly as arguments or change your code to prevent arrays reusing, e.g.:

#Main function
def Teuler(x0,y0,A,B,cre=0.1,limite=20,delta=5,arr=None):
    if arr is None:
        arr = ([],[])

For further reading can recommend Python Anti-Patterns


Post a Comment for "Matplotlib Plot Shows An Unnecessary Diagonal Line"