1 people like it.

Euler

Euler method is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
// [snippet:Euler function]
let euler f a b n y0 =
    let h = (b - a) / (float) n
    let rec euler f x y0 h =
        match x with
        | x0::x1::xt -> let y1 = y0 + f(x0,y0) * h
                        let yx = y0 + (f(x0,y0) + f(x1,y1)) / 2.0 * h
                        printfn "%.06f %.06f %.06f" x1 y1 yx
                        euler f ([x1]@xt) yx h
        | _ -> y0
    euler f [a..h..b] y0 h

// [snippet:Usage]
//This is the function values

let k1 = 0.00002
let k2 = 0.0001
let m = 100000.0
let x0 = 99000.0
let f(x,y) = k2*(m-y-x0*exp(-k1/k2*y))

let a = 0.0
let b = 10.0
let n = 5 // (b - a) / 2.0
let y = 5213.95256

euler f a b n y
val euler : f:(float * float -> float) -> a:float -> b:float -> n:int -> y0:float -> float

Full name: Script.euler
val f : (float * float -> float)
val a : float
val b : float
val n : int
val y0 : float
val h : float
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
val euler : ((float * float -> float) -> float list -> float -> float -> float)
val x : float list
val x0 : float
val x1 : float
val xt : float list
val y1 : float
val yx : float
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val k1 : float

Full name: Script.k1
val k2 : float

Full name: Script.k2
val m : float

Full name: Script.m
val x0 : float

Full name: Script.x0
val f : x:'a * y:float -> float

Full name: Script.f
val x : 'a
val y : float
val exp : value:'T -> 'T (requires member Exp)

Full name: Microsoft.FSharp.Core.Operators.exp
val a : float

Full name: Script.a
val b : float

Full name: Script.b
val n : int

Full name: Script.n
val y : float

Full name: Script.y
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/7RU
Posted:7 years ago
Author:Ivan Padron
Tags: math , mathematic