2

The plot is not centered in zero because as there is an infinite result when x takes the value = 0. How can I solve this issue and have the graphic centered in zero?

import math
import numpy as np
import matplotlib.pyplot as plt

def f(start, stop, step):
    
    values = []
    for x in np.arange(start, stop, step):
        y = math.exp(-(1/(x**2)))
        values.append(y)
    return values

# usage
start = -5
stop = 5
step = 1
values = f(start, stop, step)
print(values)

# Plot the function
plt.plot(values)
plt.grid(axis = 'x')
plt.grid(axis = 'y')

# title and axis labels
plt.title("e**-(1/(x**2))")
plt.xlabel("x")
plt.ylabel("y")

# Show the plot
plt.show()

I have tried to prevent the variable x to take the zero value but the result is the same.

Sembei Norimaki
  • 745
  • 1
  • 4
  • 11
  • You have a range from -5 to 5 in steps of 1, which will inevitably get a value of 0. Change the range values (for example from -5.5 to 5.5 in steps of 1) so you don't hit the 0. Another option is use `np.linspace` so you provide a number of points instead of a step size. If the number of points is even then you will not hit 0. – Sembei Norimaki Mar 16 '23 at 10:37
  • Changing the range as you indicated does not solve the problem as the curves are still centered between x= 4 and x = 6. The curves should touch the x axe in x = 0 and y = 0. – ZeroDarKoffee Mar 16 '23 at 18:03
  • how could be the curves be centered between x=4 and x=6 if you put a range for x between -5.5 and 5.5? For some strange reason you are just doing `plt.plot(values)` instead of also giving the x values to the plot, you should do `plt.plot(x, values)` otherwise matplotlib will just assign autonumeric values to x starting in 0. You function needs to return not only values but also the associated x to each value, so you can plot it outside the function – Sembei Norimaki Mar 16 '23 at 18:30
  • Also, "The curves should touch the x axe in x = 0" is false. in x=0 the function `math.exp(-(1/(x**2)))` is undefined to it won't touch the x axis. The limit from the left and from the right might approach a value of y=0, but in x=0 the function is not defined. – Sembei Norimaki Mar 16 '23 at 18:32
  • Of course the function is undefinied in x =0, that is the point. I meant that the plot of my code was moved to x =5 but thanks for your suggestions and help :) – ZeroDarKoffee Mar 16 '23 at 19:39

0 Answers0