Numerical integration: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 3,088: | Line 3,088: | ||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Also works with gojq, the Go implementation of jq.''' |
|||
The five different integration methods are each presented as independent functions |
|||
to facilitate reuse. |
|||
<syntaxhighlight lang=jq> |
|||
def integrate_left($a; $b; $n; f): |
|||
(($b - $a) / $n) as $h |
|||
| reduce range(0;$n) as $i (0; |
|||
($a + $i * $h) as $x |
|||
| . + ($x|f) ) |
|||
| . * $h; |
|||
def integrate_mid($a; $b; $n; f): |
|||
(($b - $a) / $n) as $h |
|||
| reduce range(0;$n) as $i (0; |
|||
($a + $i * $h) as $x |
|||
| . + (($x + $h/2) | f) ) |
|||
| . * $h; |
|||
def integrate_right($a; $b; $n; f): |
|||
(($b - $a) / $n) as $h |
|||
| reduce range(1; $n + 1) as $i (0; |
|||
($a + $i * $h) as $x |
|||
| . + ($x|f) ) |
|||
| . * $h; |
|||
def integrate_trapezium($a; $b; $n; f): |
|||
(($b - $a) / $n) as $h |
|||
| reduce range(0;$n) as $i (0; |
|||
($a + $i * $h) as $x |
|||
| . + ( ($x|f) + (($x + $h)|f)) / 2 ) |
|||
| . * $h; |
|||
def integrate_simpson($a; $b; $n; f): |
|||
(($b - $a) / $n) as $h |
|||
| reduce range(0;$n) as $i (0; |
|||
($a + $i * $h) as $x |
|||
| . + ((( ($x|f) + 4 * (($x + ($h/2))|f) + (($x + $h)|f)) / 6)) ) |
|||
| . * $h; |
|||
def demo($a; $b; $n; f): |
|||
"Left = \(integrate_left($a;$b;$n;f))", |
|||
"Mid = \(integrate_mid ($a;$b;$n;f))", |
|||
"Right = \(integrate_right($a;$b;$n;f))", |
|||
"Trapezium = \(integrate_trapezium($a;$b;$n;f))", |
|||
"Simpson = \(integrate_simpson($a;$b;$n;f))", |
|||
"" ; |
|||
demo(0; 1; 100; .*.*. ), |
|||
demo(1; 100; 1000; 1 / . ), |
|||
demo(0; 5000; 5000000; . ), |
|||
demo(0; 6000; 6000000; . ) |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
Left = 0.24502500000000005 |
|||
Mid = 0.24998750000000006 |
|||
Right = 0.25502500000000006 |
|||
Trapezium = 0.250025 |
|||
Simpson = 0.25 |
|||
Left = 4.65499105751468 |
|||
Mid = 4.604762548678376 |
|||
Right = 4.55698105751468 |
|||
Trapezium = 4.605986057514676 |
|||
Simpson = 4.605170384957133 |
|||
Left = 12499997.5 |
|||
Mid = 12500000 |
|||
Right = 12500002.5 |
|||
Trapezium = 12500000 |
|||
Simpson = 12500000 |
|||
Left = 17999997.000000004 |
|||
Mid = 17999999.999999993 |
|||
Right = 18000003.000000004 |
|||
Trapezium = 17999999.999999993 |
|||
Simpson = 17999999.999999993 |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |