Euler method: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: added simple plot and online link)
m (syntax highlighting fixup automation)
Line 65:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F euler(f, y0, a, b, h)
V t = a
V y = y0
Line 75:
V newtoncooling = (time, temp) -> -0.07 * (temp - 20)
 
euler(newtoncooling, 100.0, 0.0, 100.0, 10.0)</langsyntaxhighlight>
{{out}}
<pre>
Line 93:
=={{header|Ada}}==
The solution is generic, usable for any floating point type. The package specification:
<syntaxhighlight lang="ada">
<lang Ada>
generic
type Number is digits <>;
Line 105:
) return Waveform;
end Euler;
</syntaxhighlight>
</lang>
The function Solve returns the solution of the differential equation for each of N+1 points, starting from the point T0. The implementation:
<syntaxhighlight lang="ada">
<lang Ada>
package body Euler is
function Solve
Line 125:
end Solve;
end Euler;
</syntaxhighlight>
</lang>
The test program:
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Euler;
Line 146:
end loop;
end Test_Euler_Method;
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 167:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<langsyntaxhighlight lang="algol68">#
Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and
t=a..b and the step size h.
Line 190:
main: (
euler(newton cooling law, 100, 0, 100, 10)
)</langsyntaxhighlight>
Ouput:
<pre>
Line 210:
Which is
{{Trans|D}}
<langsyntaxhighlight lang="algolw">begin % Euler's method %
% Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h. %
real procedure euler ( real procedure f; real value y0, a, b, h ) ;
Line 230:
 
euler( newtonCoolingLaw, 100, 0, 100, 10 )
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 248:
=={{header|BASIC}}==
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> PROCeuler("-0.07*(y-20)", 100, 0, 100, 2)
PROCeuler("-0.07*(y-20)", 100, 0, 100, 5)
PROCeuler("-0.07*(y-20)", 100, 0, 100, 10)
Line 262:
t += s
ENDWHILE
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 286:
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight FreeBASIClang="freebasic">'Freebasic .9
'Custom rounding
#define round(x,N) Rtrim(Rtrim(Left(Str((x)+(.5*Sgn((x)))/(10^(N))),Instr(Str((x)+(.5*Sgn((x)))/(10^(N))),".")+(N)),"0"),".")
Line 310:
Euler(-.07*(y-20),100,0,100,10,"print")
Sleep
</syntaxhighlight>
</lang>
outputs (steps 5 and 10)
<pre>
Line 364:
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="rinbasic">x = euler(-0.07,-20, 100, 0, 100, 2)
x = euler-0.07,-20, 100, 0, 100, 5)
x = euler(-0.07,-20, 100, 0, 100, 10)
Line 377:
t = t + s
WEND
END FUNCTION</langsyntaxhighlight>
<pre>===== da:-0.07 db:-20 y:100 a:0 b:100 s:2 ===================
0 100
Line 400:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
 
Line 443:
 
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text"> Time: 0 10 20 30 40 50 60 70 80 90 100
Analytic: 100.000 59.727 39.728 29.797 24.865 22.416 21.200 20.596 20.296 20.147 20.073
Step 2: 100.000 57.634 37.704 28.328 23.918 21.843 20.867 20.408 20.192 20.090 20.042
Step 5: 100.000 53.800 34.280 26.034 22.549 21.077 20.455 20.192 20.081 20.034 20.014
Step 10: 100.000 44.000 27.200 22.160 20.648 20.194 20.058 20.017 20.005 20.002 20.000</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace prog
Line 487:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 522:
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}</langsyntaxhighlight>
Last part of output:
<pre>
Line 541:
=={{header|Clay}}==
 
<syntaxhighlight lang="clay">
<lang Clay>
import printer.formatter as pf;
 
Line 558:
}
}
</syntaxhighlight>
</lang>
 
Example output:
Line 577:
=={{header|Clojure}}==
{{trans|Python}}
<langsyntaxhighlight lang="lisp">(ns newton-cooling
(:gen-class))
 
Line 598:
(doseq [q (euler newton-coolling 100 0 100 10)]
(println (apply format "%.3f %.3f" q)))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 620:
{{works with|Visual COBOL}}
The following is in the Managed COBOL dialect:
<langsyntaxhighlight lang="cobol"> DELEGATE-ID func.
PROCEDURE DIVISION USING VALUE t AS FLOAT-LONG
RETURNING ret AS FLOAT-LONG.
Line 664:
END-PERFORM
END METHOD.
END CLASS.</langsyntaxhighlight>
 
Example output:
Line 682:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;; 't' usually means "true" in CL, but we need 't' here for time/temperature.
(defconstant true 'cl:t)
(shadow 't)
Line 707:
(euler #'newton-cooling 100 0 100 2)
(euler #'newton-cooling 100 0 100 5)
(euler #'newton-cooling 100 0 100 10)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; slightly more idiomatic Common Lisp version
 
(defun newton-cooling (time temperature)
Line 721:
(loop for time from a below b by h
for y = y0 then (+ y (* h (funcall f time y)))
do (format t "~6,3F ~6,3F~%" time y)))</langsyntaxhighlight>
 
<pre>
Line 739:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.traits;
 
/// Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h.
Line 760:
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}</langsyntaxhighlight>
Last part of the output:
<pre>...
Line 781:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Euler do
def method(_, _, t, b, _) when t>b, do: :ok
def method(f, y, t, b, h) do
Line 793:
IO.puts "\nStep = #{step}"
Euler.method(f, 100.0, 0.0, 100.0, step)
end)</langsyntaxhighlight>
 
{{out}}
Line 889:
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">
-module(euler).
-export([main/0, euler/5]).
Line 928:
euler(fun cooling/2, 100, 0, 10, 100),
ok.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 944:
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function dgleuler (f,x,y0) ...
$ y=zeros(size(x)); y[1]=y0;
Line 966:
>adaptiverunge("f",x,TS)[-1] // Adaptive Runge Method
20.0729505572
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let euler f (h : float) t0 y0 =
(t0, y0)
|> Seq.unfold (fun (t, y) -> Some((t,y), ((t + h), (y + h * (f t y)))))
Line 985:
|> Seq.takeWhile (fun (t,_) -> t <= b)
|> Seq.iter (printfn "%A")
0</langsyntaxhighlight>
Output for the above (step size 10)
<pre>(0.0, 100.0)
Line 1,000:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting fry io kernel locals math math.ranges
sequences ;
IN: rosetta-code.euler-method
Line 1,016:
2 5 10 [ '[ [ cooling ] 100 0 100 _ euler ] call nl ] tri@ ;
 
MAIN: euler-method-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 1,034:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: newton-cooling-law ( f: temp -- f: temp' )
20e f- -0.07e f* ;
 
Line 1,047:
100e ' newton-cooling-law 2 100 euler cr
100e ' newton-cooling-law 5 100 euler cr
100e ' newton-cooling-law 10 100 euler cr</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|2008}}
<langsyntaxhighlight lang="fortran">program euler_method
use iso_fortran_env, only: real64
implicit none
Line 1,107:
end function
 
end program</langsyntaxhighlight>
Output for <code>h = 10</code>:
<pre>
Line 1,130:
determined temperature (so we are computing the error).
 
<syntaxhighlight lang="futhark">
<lang Futhark>
let analytic(t0: f64) (time: f64): f64 =
20.0 + (t0 - 20.0) * f64.exp(-0.07*time)
Line 1,146:
temps)
in temps
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,216:
fmt.Println()
}
}</langsyntaxhighlight>
Output, truncated:
<pre>
Line 1,250:
 
The ''eulerMapping'' closure produces an entire approximating sequence, expressed as a Map object. Here, ''x<sub>0</sub>'' and ''y<sub>0</sub>'' together are the first point in the sequence, the ODE initial conditions. ''h'' and ''dydx'' are again the step distance and the derivative closure. ''stopCond'' is a closure representing a "stop condition" that causes the the ''eulerMapping'' closure to stop after a finite number of steps; the given default value causes ''eulerMapping'' to stop after 100 steps.
<langsyntaxhighlight lang="groovy">def eulerStep = { xn, yn, h, dydx ->
(yn + h * dydx(xn, yn)) as BigDecimal
}
Line 1,264:
yMap
}
assert eulerMapping.maximumNumberOfParameters == 5</langsyntaxhighlight>
 
 
'''Specific Euler Method Solution for the "Temperature Diffusion" Problem''' (with Newton's derivative formula and constants for environment temperature and object conductivity given)
<langsyntaxhighlight lang="groovy">def dtdsNewton = { s, t, tR, k -> k * (tR - t) }
assert dtdsNewton.maximumNumberOfParameters == 4
 
Line 1,275:
 
def tEulerH = eulerMapping.rcurry(dtds) { s, t -> s >= 100 }
assert tEulerH.maximumNumberOfParameters == 3</langsyntaxhighlight>
 
 
'''Newton's Analytic Temperature Diffusion Solution''' (for comparison)
<langsyntaxhighlight lang="groovy">def tNewton = { s, s0, t0, tR, k ->
tR + (t0 - tR) * Math.exp(k * (s0 - s))
}
Line 1,285:
 
def tAnalytic = tNewton.rcurry(0, 100, 20, 0.07)
assert tAnalytic.maximumNumberOfParameters == 1</langsyntaxhighlight>
 
 
'''Specific solutions for 3 step sizes''' (and initial time and temperature)
<langsyntaxhighlight lang="groovy">[10, 5, 2].each { h ->
def tEuler = tEulerH.rcurry(h)
assert tEuler.maximumNumberOfParameters == 2
Line 1,302:
printf('%5.0f %8.4f %8.4f %9.6f\n', s, tA, tE, relError)
}
}</langsyntaxhighlight>
 
 
Line 1,344:
=={{header|Haskell}}==
Modular solution which separates the solver and a method. Moreover it works on a given mesh which can be irregular.
<langsyntaxhighlight Haskelllang="haskell">-- the solver
dsolveBy _ _ [] _ = error "empty solution interval"
dsolveBy method f mesh x0 = zip mesh results
where results = scanl (method f) x0 intervals
intervals = zip mesh (tail mesh)</langsyntaxhighlight>
 
It is better to use strict <code>Data.List.scanl'</code> in the solver but avoiding highlighting problems we leave lazy <code>scanl</code> function.
Line 1,354:
Some possible methods:
 
<langsyntaxhighlight lang="haskell">-- 1-st order Euler
euler f x (t1,t2) = x + (t2 - t1) * f t1 x
 
Line 1,367:
k3 = f (t1 + h/2) (x + h/2*k2)
k4 = f (t1 + h) (x + h*k3)
h = t2 - t1</langsyntaxhighlight>
 
Graphical output, using EasyPlot:
 
<langsyntaxhighlight lang="haskell">import Graphics.EasyPlot
 
newton t temp = -0.07 * (temp - 20)
Line 1,393:
where sol1 = dsolveBy euler newton [0,10..100] 100
sol2 = dsolveBy rk2 newton [0,10..100] 100
sol3 = dsolveBy rk4 newton [0,10..100] 100</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,401:
This solution works in both Icon and Unicon. It takes advantage of the <code>proc</code> procedure, which converts a string naming a procedure into a call to that procedure.
 
<syntaxhighlight lang="icon">
<lang Icon>
invocable "newton_cooling" # needed to use the 'proc' procedure
 
Line 1,424:
euler ("newton_cooling", 100, 0, 100, step_size)
end
</syntaxhighlight>
</lang>
 
Sample output:
Line 1,444:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">NB.*euler a Approximates Y(t) in Y'(t)=f(t,Y) with Y(a)=Y0 and t=a..b and step size h.
euler=: adverb define
'Y0 a b h'=. 4{. y
Line 1,453:
 
ncl=: _0.07 * -&20 NB. Newton's Cooling Law
</syntaxhighlight>
</lang>
'''Example:'''
<langsyntaxhighlight lang="j"> ncl euler 100 0 100 2
... NB. output redacted for brevity
ncl euler 100 0 100 5
Line 1,470:
80 20.0052
90 20.0016
100 20.0005</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">
public class Euler {
private static void euler (Callable f, double y0, int a, int b, int h) {
Line 1,508:
}
}
</syntaxhighlight>
</lang>
 
Output for step = 10;
Line 1,528:
=={{header|JavaScript}}==
{{trans|Python}}
<langsyntaxhighlight lang="javascript">
// Function that takes differential-equation, initial condition,
// ending x, and step size as parameters
Line 1,558:
 
eulersMethod(cooling, 0, 100, 100, 10);
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># euler_method takes a filter (df), initial condition
# (x1,y1), ending x (x2), and step size as parameters;
# it emits the y values at each iteration.
Line 1,586:
# The following solves the task:
# (2,5,10) | [., [ euler_method(cooling; 0; 100; 100; .) ] ]
</syntaxhighlight>
</lang>
For brevity, we modify euler_method so that it only shows the final value of y:
<syntaxhighlight lang="jq">
<lang jq>
def euler_solution(df; x1; y1; x2; h):
def recursion(exp): reduce recurse(exp) as $x (.; $x);
Line 1,598:
else empty
end )
| .[1] ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">(1,2,5,10,20) | [., [ euler_solution(cooling; 0; 100; 100; .) ] ]</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -n -c -f Euler_method.jq
[1,[20.05641373347389]]
[2,[20.0424631833732]]
[5,[20.01449963666907]]
[10,[20.000472392]]
[20,[19.180799999999998]]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.0.3}}
<langsyntaxhighlight lang="julia">euler(f::Function, T::Number, t0::Int, t1::Int, h::Int) = collect(begin T += h * f(T); T end for t in t0:h:t1)
 
# Prints a series of arbitrary values in a tabular form, left aligned in cells with a given width
Line 1,626:
end
println()
end</langsyntaxhighlight>
 
{{out}}
Line 1,671:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
typealias Deriv = (Double) -> Double // only one parameter needed here
Line 1,702:
for (i in listOf(2, 5, 10))
euler(::cooling, 100.0, i, 100)
}</langsyntaxhighlight>
 
{{out}}
Line 1,715:
=={{header|Lambdatalk}}==
Translation of Python
<langsyntaxhighlight lang="scheme">
{def eulersMethod
{def eulersMethod.r
Line 1,743:
90 20.002
100 20
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">T0 = 100
TR = 20
k = 0.07
Line 1,768:
Euler( NewtonCooling, T0, n, delta_t[i] )
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Build-in function with Euler:
<langsyntaxhighlight Maplelang="maple">with(Student[NumericalAnalysis]);
k := 0.07:
TR := 20:
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 50); # step size = 2
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 20); # step size = 5
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 10); # step size = 10</langsyntaxhighlight>
{{out}}
<pre>
Line 1,785:
</pre>
Hard-coded procedure:
<langsyntaxhighlight Maplelang="maple">f := y -> (-0.07) * (y - 20):
 
EulerMethod := proc(f, start_time, end_time, y0, h) # y0: initial value #h: step size
Line 1,810:
# step size = 10
printf("\nStep Size = %a\n", 10);
EulerMethod(f, 0, 100, 100, 10);</langsyntaxhighlight>
{{out}}
<pre style="height: 40ex; overflow: scroll">
Line 1,905:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Better methods for differential equation solving are built into Mathematica, so the typical user would omit the Method and StartingStepSize options in the code below. However since the task requests Eulers method, here is the bad solution...
<syntaxhighlight lang="mathematica">
<lang Mathematica>
euler[step_, val_] := NDSolve[
{T'[t] == -0.07 (T[t] - 20), T[0] == 100},
Line 1,912:
StartingStepSize -> step
][[1, 1, 2]][val]
</syntaxhighlight>
</lang>
{{out}}
<pre>euler[2, 100]
Line 1,924:
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">euler_method(f, y0, a, b, h):= block(
[t: a, y: y0, tg: [a], yg: [y0]],
unless t>=b do (
Line 1,962:
[xlabel, "t / seconds"],
[ylabel, "Temperature / C"]);
</syntaxhighlight>
</lang>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П2 С/П П3 С/П П4 ПП 19 ИП3 * ИП4
+ П4 С/П ИП2 ИП3 + П2 БП 05 ...
... ... ... ... ... ... ... ... ... В/О</langsyntaxhighlight>
 
Instead of dots typed calculation program equation ''f(u, t)'', where the arguments are ''t'' = Р2, ''u'' = Р4.
Line 1,976:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc euler(f: proc (x,y: float): float; y0, a, b, h: float) =
Line 1,988:
-0.07 * (temp - 20)
 
euler(newtoncooling, 100.0, 0.0, 100.0, 10.0)</langsyntaxhighlight>
 
{{out}}
Line 2,003:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class EulerMethod {
T0 : static : Float;
Line 2,036:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 2,056:
=={{header|OCaml}}==
 
<langsyntaxhighlight OCamllang="ocaml">(* Euler integration by recurrence relation.
* Given a function, and stepsize, provides a function of (t,y) which
* returns the next step: (t',y'). *)
Line 2,065:
 
(* analytic solution for Newton cooling *)
let analytic_solution ~k ~tr ~t0 t = tr +. (t0 -. tr) *. exp (-.k *. t)</langsyntaxhighlight>
 
Using the above functions to produce the task results:
<langsyntaxhighlight OCamllang="ocaml">(* Wrapping up the parameters in a "cool" function: *)
let cool = euler (newton_cooling ~k:0.07 ~tr:20.)
 
Line 2,091:
results (cool ~step:10.)
results (cool ~step:5.)
results (cool ~step:2.)</langsyntaxhighlight>
 
Example output:
Line 2,113:
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">: euler(f, y, a, b, h)
| t |
a b h step: t [
System.Out t <<wjp(6, JUSTIFY_RIGHT, 3) " : " << y << cr
t y f perform h * y + ->y
] ;</langsyntaxhighlight>
 
Usage :
 
<langsyntaxhighlight lang="oforth">: newtonCoolingLaw(t, y)
y 20 - -0.07 * ;
 
Line 2,128:
euler(#newtonCoolingLaw, 100.0, 0.0, 100.0, 2)
euler(#newtonCoolingLaw, 100.0, 0.0, 100.0, 5)
euler(#newtonCoolingLaw, 100.0, 0.0, 100.0, 10) ;</langsyntaxhighlight>
 
{{out}}
Line 2,151:
Euler code for Free Pascal - Delphi mode. Apart from the function-pointer calling convention for the NewtonCooling method, this example is ISO-7185 standard Pascal.
 
<syntaxhighlight lang="pascal">
<lang Pascal>
 
{$mode delphi}
Line 2,203:
END.
 
</syntaxhighlight>
</lang>
 
 
Line 2,218:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">sub euler_method {
my ($t0, $t1, $k, $step_size) = @_;
my @results = ( [0, $t0] );
Line 2,250:
$an;
}
</syntaxhighlight>
</lang>
Output:<pre>Time 2 err(%) 5 err(%) 10 err(%) Analytic
----------------------------------------------------------------------------
Line 2,269:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/euler_method.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Euler_method.exw
Line 2,325:
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,336:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de euler (F Y A B H)
Line 2,349:
(euler newtonCoolingLaw 100.0 0 100.0 2.0)
(euler newtonCoolingLaw 100.0 0 100.0 5.0)
(euler newtonCoolingLaw 100.0 0 100.0 10.0)</langsyntaxhighlight>
Output:
<pre>...
Line 2,364:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">test: procedure options (main); /* 3 December 2012 */
 
declare (x, y, z) float;
Line 2,407:
end f;
 
end test;</langsyntaxhighlight>
 
Only the final two outputs are shown, for brevity.
Line 2,451:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function euler (${f}, ${y}, $y0, $t0, $tEnd) {
function f-euler ($tn, $yn, $h) {
Line 2,495:
}
euler f y $y0 $t0 $tEnd | Format-Table -AutoSize
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,514:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Define.d
Prototype.d Func(Time, t)
 
Line 2,538:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
<pre>...
85.000 20.053
Line 2,558:
=={{header|Python}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang="python">def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
Line 2,569:
 
euler(newtoncooling,100,0,100,10)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,587:
=={{header|R}}==
{{trans|Python}}
<langsyntaxhighlight lang="rsplus">euler <- function(f, y0, a, b, h)
{
t <- a
Line 2,604:
}
 
euler(newtoncooling, 100, 0, 100, 10)</langsyntaxhighlight>
Output:
<pre> 0.000 100.000
Line 2,620:
 
The ODE solver:
<langsyntaxhighlight lang="racket">
(define (ODE-solve f init
#:x-max x-max
Line 2,627:
(reverse
(iterate-while (λ (x . y) (<= x x-max)) (method f h) init)))
</syntaxhighlight>
</lang>
 
It uses the default integration method <tt>euler</tt>, defined separately.
 
<langsyntaxhighlight lang="racket">
(define (euler F h)
(λ (x y) (list (+ x h) (+ y (* h (F x y))))))
</syntaxhighlight>
</lang>
 
A general-purpose procedure which evalutes a given function ''f'' repeatedly starting with argument ''x'', while all results satisfy a predicate ''test''. Returns a list of iterations.
 
<langsyntaxhighlight lang="racket">
(define (iterate-while test f x)
(let next ([result x]
Line 2,645:
(next (apply f result) (cons result list-of-results))
list-of-results)))
</syntaxhighlight>
</lang>
 
Textual output:
<langsyntaxhighlight lang="racket">
> (define (newton-cooling t T)
(* -0.07 (- T 20)))
Line 2,663:
(90 20.00157464)
(100 20.000472392))
</syntaxhighlight>
</lang>
 
Plotting results:
<langsyntaxhighlight lang="racket">
> (require plot)
> (plot
Line 2,676:
'(red blue black))
#:legend-anchor 'top-right)
</syntaxhighlight>
</lang>
[[File:euler1.jpg]]
 
Line 2,682:
[http://en.wikipedia.org/wiki/Midpoint_method 2-nd order Runge-Kutta method]:
 
<langsyntaxhighlight lang="racket">
(define (RK2 F h)
(λ (x y)
(list (+ x h) (+ y (* h (F (+ x (* 1/2 h))
(+ y (* 1/2 h (F x y)))))))))
</syntaxhighlight>
</lang>
 
[http://en.wikipedia.org/wiki/Adams_method#Two-step_Adams.E2.80.93Bashforth Two-step Adams–Bashforth method]
<langsyntaxhighlight lang="racket">
(define (adams F h)
(case-lambda
Line 2,698:
(let ([f (F x y)])
(list (+ x h) (+ y (* 3/2 h f) (* -1/2 h f′)) f))]))
</syntaxhighlight>
</lang>
 
[http://en.wikipedia.org/wiki/Adaptive_stepsize Adaptive one-step method] modifier using absolute accuracy ''ε''
<langsyntaxhighlight lang="racket">
(define ((adaptive method ε) F h0)
(case-lambda
Line 2,713:
(list x1 (+ y1 τ) (* 2 h′)))]))
 
</syntaxhighlight>
</lang>
 
Comparison of different integration methods
<langsyntaxhighlight lang="racket">
> (define (solve-newton-cooling-by m)
(ODE-solve newton-cooling '(0 100)
Line 2,735:
#:color 'blue #:label "Adaptive Runge-Kutta"))
#:legend-anchor 'top-right)
</syntaxhighlight>
</lang>
 
[[File:euler2.jpg]]
Line 2,743:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub euler ( &f, $y0, $a, $b, $h ) {
my $y = $y0;
my @t_y;
Line 2,779:
say $t.fmt('%4d '), ( $exact, $a, $b, $c )».fmt(' %7.3f'),
$err.([$a, $b, $c])».fmt(' %7.3f%%');
}</langsyntaxhighlight>
 
Output:<pre>Time Analytic Step2 Step5 Step10 Err2 Err5 Err10
Line 2,797:
===version 1===
{{trans|PLI}}
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 24.05.2013 Walter Pachl translated from PL/I
**********************************************************************/
Line 2,869:
r=r+0
Return r
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,922:
 
<br>It also shows the percentage difference (analytic vs. Euler's method) for each calculation.
<langsyntaxhighlight lang="rexx">/*REXX pgm solves example of Newton's cooling law via Euler's method (diff. step sizes).*/
e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138
numeric digits length(e) - length(.) /*use the number of decimal digits in E*/
Line 2,946:
exp: procedure expose e; arg x; ix= x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x= x-ix; z=1
_=1; w=1; do j=1; _= _*x/j; z= (z+_)/1; if z==w then leave; w=z
end /*j*/; if z\==0 then z= e**ix * z; return z</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,045:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(3)
see euler("return -0.07*(y-20)", 100, 0, 100, 2) + nl
Line 3,058:
t += s
end
return y</langsyntaxhighlight>
Output:
<pre>
Line 3,071:
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def euler(y, a, b, h)
a.step(b,h) do |t|
puts "%7.3f %7.3f" % [t,y]
Line 3,082:
euler(100,0,100,step) {|time, temp| -0.07 * (temp - 20) }
puts
end</langsyntaxhighlight>
{{out}}
<pre style="height: 40ex; overflow: scroll">
Line 3,177:
=={{header|Rust}}==
{{trans|Kotlin}}
<langsyntaxhighlight Rustlang="rust">fn header() {
print!(" Time: ");
for t in (0..100).step_by(10) {
Line 3,210:
euler(|temp| -0.07 * (temp - 20.0), 100.0, i, 100);
}
}</langsyntaxhighlight>
{{out}}
<pre> Time: 0 10 20 30 40 50 60 70 80 90
Line 3,220:
=={{header|Scala}}==
 
<langsyntaxhighlight lang="scala">
object App{
 
Line 3,250:
 
}
</syntaxhighlight>
</lang>
 
Output for step = 10;
Line 3,270:
=={{header|SequenceL}}==
 
<langsyntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
 
Line 3,294:
output when x > n
else
euler(f, newY, n, h, newX, newOutput);</langsyntaxhighlight>
Based on C# version [http://rosettacode.org/wiki/Euler_method#C.23] but using tail recursion instead of looping.
{{out}}
Line 3,317:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func euler_method(t0, t1, k, step_size) {
var results = [[0, t0]]
for s in (step_size..100 -> by(step_size)) {
Line 3,346:
r10[i][1], (r10[i][1] / an) * 100 - 100,
an)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,365:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">ODESolver>>eulerOf: f init: y0 from: a to: b step: h
| t y |
t := a.
Line 3,378:
 
ODESolver new eulerOf: [:time :temp| -0.07 * (temp - 20)] init: 100 from: 0 to: 100 step: 10
</syntaxhighlight>
</lang>
Transcript:
<pre>
Line 3,395:
=={{header|Swift}}==
{{trans|C}}
<langsyntaxhighlight lang="swift">import Foundation
 
let numberFormat = " %7.3f"
Line 3,436:
ivpEuler(function: cooling, initialValue: initialTemp, step: 2)
ivpEuler(function: cooling, initialValue: initialTemp, step: 5)
ivpEuler(function: cooling, initialValue: initialTemp, step: 10)</langsyntaxhighlight>
 
{{out}}
Line 3,449:
=={{header|Tcl}}==
{{trans|C++}}
<langsyntaxhighlight lang="tcl">proc euler {f y0 a b h} {
puts "computing $f over \[$a..$b\], step $h"
set y [expr {double($y0)}]
Line 3,457:
}
puts "done"
}</langsyntaxhighlight>
Demonstration with the Newton Cooling Law:
<langsyntaxhighlight lang="tcl">proc newtonCoolingLaw {time temp} {
expr {-0.07 * ($temp - 20)}
}
Line 3,465:
euler newtonCoolingLaw 100 0 100 2
euler newtonCoolingLaw 100 0 100 5
euler newtonCoolingLaw 100 0 100 10</langsyntaxhighlight>
End of output:
<pre>
Line 3,484:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)
Dim t As Integer
Debug.Print " Step "; step; ": ",
Line 3,519:
ivp_euler r_cooling, 100, 5, 100
ivp_euler r_cooling, 100, 10, 100
End Sub</langsyntaxhighlight>{{out}}
<pre> Time: 0 10 20 30 40 50 60 70 80 90 100
Analytic: 100,000 59,727 39,728 29,797 24,865 22,416 21,200 20,596 20,296 20,147 20,073
Line 3,528:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="go">import math
// Fdy is a type for fntion f used in Euler's method.
type Fdy = fn(f64, f64) f64
Line 3,588:
println('')
}
}</langsyntaxhighlight>
Output, truncated:
<pre>
Line 3,613:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Euler(Step); \Display cooling temperatures using Euler's method
Line 3,650:
Euler(5);
Euler(10);
]</langsyntaxhighlight>
 
Output:
Line 3,665:
{{libheader|Wren-fmt}}
{{libheader|Wren-trait}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/trait" for Stepped
 
Line 3,689:
 
analytic.call()
for (i in [2, 5, 10]) euler.call(cooling, 100, i, 100)</langsyntaxhighlight>
 
{{out}}
Line 3,702:
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">const FMT=" %7.3f";
fcn ivp_euler(f,y,step,end_t){
Line 3,726:
ivp_euler(cooling, 100.0, 2, 100);
ivp_euler(cooling, 100.0, 5, 100);
ivp_euler(cooling, 100.0, 10, 100);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,738:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET d$="-0.07*(y-20)": LET y=100: LET a=0: LET b=100: LET s=10
20 LET t=a
30 IF t<=b THEN PRINT t;TAB 10;y: LET y=y+s*VAL d$: LET t=t+s: GO TO 30</langsyntaxhighlight>
10,327

edits