Kalkulus 2.3

mail@pastecode.io avatar
unknown
python
2 years ago
1.3 kB
2
Indexable
Never
import numpy as np
def g(x):
  y = np.e**(x**2/2)
  return y

# Latihan 2.3 bagian a
def RK4(x_end, step_size):
  def f(x, y):
    return x*y

  x = 0
  xfin = x_end
  y = 1
  h = step_size
  xlist = []
  ylist = [1.0]

  j = 0
  while j >= 0:
    xj = x + j*h
    if xj > xfin:
      break
    xlist.append(xj)
    j += 1

  for x in xlist:
    k1 = f(x, y)
    k2 = f(x + h/2, y + k1*h/2)
    k3 = f(x + h/2, y + k2*h/2)
    k4 = f(x + h, y + k3*h)
    yi = y + (k1 + 2*k2 + 2*k3 +k4)*h/6
    ylist.append(yi)
    y = yi

  del ylist[len(ylist)-1]
  return [xlist, ylist]

xlist_RK4 = RK4(2, 0.5)[0]
ylist_RK4 = RK4(2, 0.5)[1]

ylistanl = []
for k in xlist_RK4:
  ylistanl.append(g(k))

print(33*"-") ; print(3*" ", "METODE RUNGE KUTTA ORDE 4", 2*" ") ; print(33*"-")
dict4 = {}
for l in range(len(xlist_RK2)):
  dict4[l+1] = [xlist_RK4[l], ylist_RK4[l], ylistanl[l]]
print ("{:<4} {:<6} {:<10} {:<10}".format('No','x','y numerik','y analitik'))
for n, v in dict4.items():
    x, y_numerik, y_analitik = v
    print ("{:<4} {:<6.1f} {:<10.5f} {:<10.5f}".format(n, x, y_numerik, y_analitik))
print('')

# Latihan 2.3 bagian b
import matplotlib.pyplot as plt

xfine = np.linspace(0, 2, 100)
yfine = g(xfine)

plt.plot(xlist_RK4, ylist_RK4, 'o-m', xfine, yfine, '-k')
plt.legend(['Runge Kutta orde 4', 'Analitik'])
plt.show()