Controlling matplotlib plot interval, 100% RAM usage problem

Hello Stackoverflow community:)

I am developing a small code that plots the graph from 2 lists filled from an equation as long as a while condition is not satisfied.

As soon as the lists are filled, I use matplotlib to plot the two-dimensional graph with the extracted values, but they are many values and I would like to know if you can plot only points at specific intervals, because if I plot all, the memory usage of my PC goes up to 100% and Python crashes and gives memory error. Would you have a way to optimize this process?

For example, using the interval of one in one nanometer (which is the case I'm trying to solve)

# Modelando a energia do fóton em uma equação

from matplotlib import pyplot as plt

h = 1.05457168 * 10**(-34) # J * s
c = 299792458.0 #m/s
i = 0.000004 #metros
energias =[] 
wavelenghts=[]


while (i!=0.000007):
    E = (h*c)/i
    energias.append(E)
    wavelenghts.append(i)
    i=i+0.000001

print (energias)
print (wavelenghts)

plt.plot (energias, wavelenghts, color='blue', marker = 'o', linestyle = 'solid')
Author: Kioolz, 2020-01-21

1 answers

Maybe the problem is with the accuracy of the variable. Change line 12 of

while (i!=0.000007):

For

while (i<=0.000007): # menor ou igual a 0.000007

The comment below @EltonNunes is perfect. Just complementing: inequality comparisons (!=) are problematic when using floating point operations given the inaccuracy as calculation involves more and more decimal places as a result of the IEEE-754 specification.

Another way to avoid this behavior would be by keeping the its loop with an integer variable, thus preserving the behavior expected by the inequality comparison:

i = 4 #metros
[...]

while (i!=7):
    vi = i/1000000
    E = (h*c)/vi
    energias.append(E)
    wavelenghts.append(vi)
    i=i+1
 1
Author: OnoSendai, 2020-01-21 18:25:44