Sharedcloud-examples / sage / 2018-02-08-195444_Método_de_Euler.sagewsOpen in CoCalc
Método de Euler
# -*- coding: utf-8 -*-
# Método de Euler
import numpy as np
import matplotlib.pyplot as plt
import math

def function(x,y):
    f=-x/y
    return f

def sol_exacta(x,y):
    g=sqrt(64-x**2)
    return g

x0=0
xf=8
y0=8
n=5
h=(xf-x0)/n


x=np.zeros(n)
y=np.zeros(n)
ye=np.zeros(n)

x[0]=x0
y[0]=y0
ye[0]=y0

print('x','y_euler','y_exacta')
print(x[0],y[0],ye[0])
for i in range(n-1):
    x[i+1]=x[i]+h
    y[i+1]=y[i]+h*function(x[i],y[i])
    ye[i+1]=sol_exacta(x[i+1],y[i+1])
    print(x[i+1],y[i+1],ye[i+1])

t=np.linspace(x0,xf,1000)
plt.plot(x,y,'b-')
plt.plot(t,sol_exacta(t,y),'g-')
plt.grid(true)
plt.show()
('x', 'y_euler', 'y_exacta') (0.0, 8.0, 8.0) (1.6, 8.0, 7.83836717690617) (3.2, 7.68, 7.332121111929344) (4.800000000000001, 7.013333333333333, 6.3999999999999995) (6.4, 5.9182762991128, 4.799999999999999) [<matplotlib.lines.Line2D object at 0x7fe68d5a3b90>] [<matplotlib.lines.Line2D object at 0x7fe68d5b2150>]