Kalkulus 2.2

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

# Latihan 2.2 bagian a
import numpy as np

def RK2(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, y + k1*h)
    yi = y + (k1 + k2)*h/2
    ylist.append(yi)
    y = yi

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

xlist_RK2 = RK2(2, 0.5)[0]
ylist_RK2 = RK2(2, 0.5)[1]

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

print(33*"-") ; print(3*" ", "METODE RUNGE KUTTA ORDE 2", 2*" ") ; print(33*"-")
dict3 = {}
for l in range(len(xlist_RK2)):
  dict3[l+1] = [xlist_RK2[l], ylist_RK2[l], ylistanl[l]]
print ("{:<4} {:<6} {:<10} {:<10}".format('No','x','y numerik','y analitik'))
for n, v in dict3.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.2 bagian b
import matplotlib.pyplot as plt

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

plt.plot(xlist_RK2, ylist_RK2, 'o-b', xfine, yfine, '-k')
plt.legend(['Runge Kutta orde 2', 'Analitik'])
plt.show()