eulers_method.py

Created by nick-koberstein

Created on September 22, 2021

942 Bytes

In this Python program x0 and y0 represent the initial condition. xn is the calculation point on which the value of yn corresponding to xn is to be calculated using Euler’s method. step represents number of finite step before reaching to xn.


from math import *

# Euler method python program

# function to be solved
def f(x,y):
    return 18*x*sin(0.79*x)

# Euler method
def euler(x0,y0,xn,n):
    
    # Calculating step size
    h = (xn-x0)/n
    
    print('\n-----------SOLUTION-----------')
    print('------------------------------')    
    print('x0\ty0\tslope\tyn')
    print('------------------------------')
    for i in range(n):
        slope = f(x0, y0)
        yn = y0 + h * slope
        print('%.3f\t%.3f\t%0.3f\t%.3f'% (x0,y0,slope,yn) )
        print('------------------------------')
        y0 = yn
        x0 = x0+h
    
    print('\nAt x=%.4f, y=%.4f' %(xn,yn))

# Inputs
print('Enter initial conditions:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))

print('Enter calculation point: ')
xn = float(input('xn = '))

print('Enter number of steps:')
step = int(input('Number of steps = '))

# Euler method call
euler(x0,y0,xn,step)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.