Created
September 23, 2020 06:12
-
-
Save nandanhere/bf02f9862ebf3a022f45b4a8e5a6d45f to your computer and use it in GitHub Desktop.
[Solve a differential equation using 4th order Runge kutta method] An algorithm to solve a Differential equation given the points of x and initial value of y #swift #differential_equations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Solving a differential equation using 4th order runge kutta method | |
///ALL VARIABLES ARE TO BE IN DOUBLE | |
/// note the given values are an example. you can replace your own values if you want | |
let xes :[Double] = [0.0,0.1] // you must input the xn values you want to calculate for | |
var yn = 1.0 // initial value of y (y0) | |
let h = 0.1 // the value by which x increments in each step | |
var xn = xes[0] | |
func dE(_ x : Double,_ y : Double) -> Double | |
{ | |
return (3 * x) + (y / 2) // replace this with the given f(x,y) | |
} | |
func k1() -> Double | |
{ | |
return h * (dE(xn, yn)) | |
} | |
func k2() -> Double | |
{ | |
return h * (dE(xn + (h / 2), yn + (k1() / 2 ))) | |
} | |
func k3() -> Double | |
{ | |
return h * (dE(xn + (h / 2), yn + (k2() / 2))) | |
} | |
func k4() -> Double | |
{ | |
return h * (dE(xn + (h / 2), yn + k3())) | |
} | |
func ynext() -> Double | |
{ | |
let K1 = k1() | |
let K2 = k2() | |
let K3 = k3() | |
let K4 = k4() | |
return yn + ((K1 + (2 * (K2 + K3)) + K4) / 6) | |
} | |
for i in 0 ..< xes.count | |
{ | |
xn = xes[i] | |
print("x\(i) = \(xn)") | |
print("k1 = \(k1())") | |
print("k2 = \(k2())") | |
print("k3 = \(k3())") | |
print("k4 = \(k4())") | |
yn = ynext() | |
print("y\(i + 1) = \(yn)\n") | |
} | |
// code will print the value of yn+1 at the given xn and yn values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment