-3

I have some problems with plot. Exatlct solution here is true, but eulerbmethod gives the same curve, but much lower

import numpy as np
import matplotlib.pyplot as plt
 
# Define parameters
f = lambda x, y: 2*x
h = 0.1
x = np.arange(-10, 10, h)
x0 = 0
y0 = 2
 
# Explicit Euler Method
y = np.zeros(len(x))
y[x0] = y0
 
for i in range(0, len(x) - 1):
    y[i + 1] = y[i] + h*f(x[i], y[i])
 
plt.figure(figsize=(12, 8))
plt.plot(x, y, 'b--', label='Euler')
plt.plot(x, 2+x**2, 'g', label='Exact')
plt.title('Numerical integration methods')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.legend()
plt.show()
  • 2
    Isn't curve height irrelevant for integrals (As in curves at any height are all proper solutions)? – matszwecja Sep 01 '22 at 14:27
  • 1
    Did you do any [debugging](//ericlippert.com/2014/03/05/how-to-debug-small-programs/)? Solve your problem by hand, and see if your program's intermediate steps perform as expected. When you find a mismatch, follow that backwards to find the source of the issue. [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953) – Pranav Hosangadi Sep 01 '22 at 14:28
  • " the same curve, but much lower" - you probably didn't choose the same initial value as `y0 = 2` in both cases. – Thierry Lathuille Sep 01 '22 at 14:39

1 Answers1

1

That's because your "exact solution" is not correct. When you integrate, you have to consider that you have a non-zero value for x:

enter image description here

mauro
  • 504
  • 3
  • 14