Numerical integration/Gauss-Legendre Quadrature: Difference between revisions
Numerical integration/Gauss-Legendre Quadrature (view source)
Revision as of 15:07, 10 April 2024
, 1 month agoAdded FreeBASIC
(→{{header|Wren}}: Now uses new core library method.) |
(Added FreeBASIC) |
||
(9 intermediate revisions by 7 users not shown) | |||
Line 51:
{{trans|Nim}}
<
F prev1(idx, pn1)
R (2 * idx - 1) * @x * pn1
Line 120:
R result * sum
print(‘integral: ’integ(x -> exp(x), 5, -3, 3))</
{{out}}
Line 128:
integral: 20.035577718
</pre>
=={{header|ATS}}==
{{trans|Common Lisp}}
This is a very close translation of the Common Lisp.
(A lot of the "ATS-ism" is completely optional. For instance, you can use <code>arrszref</code> instead of <code>arrayref</code>, if you want bounds checking at runtime instead of compile-time. But then debugging and regression-prevention become harder, and in that particular case the code will almost surely be slower.
And, if I may grumble a bit: ''Some'' of us ''do not'' think "turning off bounds checking for production" is acceptable. It is at best something to tolerate grudgingly.)
<syntaxhighlight lang="ats">
#include "share/atspre_staload.hats"
%{^
#include <float.h>
#include <math.h>
%}
extern fn {tk : tkind} g0float_pi : () -<> g0float tk
extern fn {tk : tkind} g0float_cos : g0float tk -<> g0float tk
extern fn {tk : tkind} g0float_exp : g0float tk -<> g0float tk
implement g0float_pi<dblknd> () = $extval (double, "M_PI")
implement g0float_cos<dblknd> x = $extfcall (double, "cos", x)
implement g0float_exp<dblknd> x = $extfcall (double, "exp", x)
macdef PI = g0float_pi ()
overload cos with g0float_cos
overload exp with g0float_exp
macdef NAN = g0f2f ($extval (float, "NAN"))
macdef Zero = g0i2f 0
macdef One = g0i2f 1
macdef Two = g0i2f 2
(* Computes the initial guess for the root i of a n-order Legendre
polynomial. *)
fn {tk : tkind}
guess {n, i : int | 1 <= i; i <= n}
(n : int n, i : int i) :<> g0float tk =
cos (PI * ((g0i2f i - g0f2f 0.25) / (g0i2f n + g0f2f 0.5)))
(* Computes and evaluates the degree-n Legendre polynomial at the
point x. *)
fn {tk : tkind}
legpoly {n : pos}
(n : int n, x : g0float tk) :<> g0float tk =
let
fun
loop {i : int | 2 <= i; i <= n + 1} .<n + 1 - i>.
(i : int i, pa : g0float tk, pb : g0float tk)
:<> g0float tk =
if i = succ n then
pb
else
let
val iflt = (g0i2f i) : g0float tk
val pn = (((iflt + iflt - One) / iflt) * x * pb)
- (((iflt - One) / iflt) * pa)
in
loop (succ i, pb, pn)
end
in
if n = 0 then
One
else if n = 1 then
x
else
loop (2, One, x)
end
(* Computes and evaluates the derivative of an n-order Legendre
polynomial at point x. *)
fn {tk : tkind}
legdiff {n : int | 2 <= n}
(n : int n, x : g0float tk) :<> g0float tk =
(g0i2f n / ((x * x) - One))
* ((x * legpoly<tk> (n, x)) - legpoly<tk> (pred n, x))
(* Computes the n nodes for an n-point quadrature rule (the n roots of
a degree-n polynomial). *)
fn {tk : tkind}
nodes {n : int | 2 <= n}
(n : int n) :<!refwrt> arrayref (g0float tk, n) =
let
val x = arrayref_make_elt<g0float tk> (i2sz n, Zero)
fn
v_update (v : g0float tk) :<> g0float tk =
v - (legpoly<tk> (n, v) / legdiff<tk> (n, v))
var i : Int
in
for* {i : nat | i <= n} .<n - i>.
(i : int i) =>
(i := 0; i <> n; i := succ i)
let
val v = guess<tk> (n, succ i)
val v = v_update v
val v = v_update v
val v = v_update v
val v = v_update v
val v = v_update v
in
x[i] := v
end;
x
end
(* Computes the weight for an degree-n polynomial at the node x. *)
fn {tk : tkind}
legwts {n : int | 2 <= n}
(n : int n, x : g0float tk) :<> g0float tk =
(* Here I am having slightly excessive fun with notation: *)
Two / ((One - (x * x)) * (y * y where {val y = legdiff<tk> (n, x)}))
(* Normally I would not write code in such fashion. :) Nevertheless,
it is interesting that this works. *)
(* Takes an array of nodes x and computes an array of corresponding
weights w. Note that x is an arrayref, not an arrszref, and so
(unlike in the Common Lisp) we have to tell the function the size
of the new array w. That information is not otherwise stored AT
RUNTIME. The ATS compiler, however, will force us AT COMPILE TIME
to pass the correct size. *)
fn {tk : tkind}
weights {n : int | 2 <= n}
(n : int n, x : arrayref (g0float tk, n))
:<!refwrt> arrayref (g0float tk, n) =
let
val w = arrayref_make_elt<g0float tk> (i2sz n, Zero)
var i : Int
in
for* {i : nat | i <= n} .<n - i>.
(i : int i) =>
(i := 0; i <> n; i := succ i)
w[i] := legwts (n, x[i]);
w
end
(* Estimates the definite integral of a function on [a,b], using an
n-point Gauss-Legendre quadrature rule. *)
fn {tk : tkind}
quad {n : int | 2 <= n}
(f : g0float tk -<> g0float tk,
n : int n,
a : g0float tk,
b : g0float tk) :<> g0float tk =
let
val x = $effmask_ref ($effmask_wrt (nodes<tk> n))
val w = $effmask_ref ($effmask_wrt (weights<tk> (n, x)))
val ahalf = g0f2f 0.5 * a and bhalf = g0f2f 0.5 * b
val C1 = bhalf - ahalf and C2 = ahalf + bhalf
fun
loop {i : nat | i <= n} .<n - i>.
(i : int i, sum : g0float tk) :<> g0float tk =
if i = n then
sum
else
let
val y = $effmask_ref (w[i] * f ((C1 * x[i]) + C2))
in
loop (succ i, sum + y)
end
in
C1 * loop (0, Zero)
end
implement
main () =
let
val outf = stdout_ref
in
fprintln! (outf, "nodes<dblknd> 5");
fprint_arrayref_sep<double> (outf, nodes<dblknd> (5),
i2sz 5, " ");
fprintln! (outf); fprintln! (outf);
fprintln! (outf, "weights (nodes<dblknd> 5)");
fprint_arrayref_sep<double> (outf, weights (5, nodes<dblknd> (5)),
i2sz 5, " ");
fprintln! (outf); fprintln! (outf);
fprintln! (outf, "quad (lam x => exp x, 5, ~3.0, 3.0) = ",
quad (lam x => exp x, 5, ~3.0, 3.0));
fprintln! (outf);
fprintln! (outf, "More examples, borrowed from the Common Lisp:");
fprintln! (outf, "quad (lam x => x ** 3, 5, 0.0, 1.0) = ",
quad (lam x => x ** 3, 5, 0.0, 1.0));
fprintln! (outf, "quad (lam x => 1.0 / x, 5, 1.0, 100.0) = ",
quad (lam x => 1.0 / x, 5, 1.0, 100.0));
fprintln! (outf, "quad (lam x => x, 5, 0.0, 5000.0) = ",
quad (lam x => x, 5, 0.0, 5000.0));
fprintln! (outf, "quad (lam x => x, 5, 0.0, 6000.0) = ",
quad (lam x => x, 5, 0.0, 6000.0));
0
end
</syntaxhighlight>
{{out}}
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_GCBDW gauss_legendre_task.dats -lgc -lm && ./a.out
nodes<dblknd> 5
0.906180 0.538469 0.000000 -0.538469 -0.906180
weights (nodes<dblknd> 5)
0.236927 0.478629 0.568889 0.478629 0.236927
quad (lam x => exp x, 5, ~3.0, 3.0) = 20.035578
More examples, borrowed from the Common Lisp:
quad (lam x => x ** 3, 5, 0.0, 1.0) = 0.250000
quad (lam x => 1.0 / x, 5, 1.0, 100.0) = 4.059148
quad (lam x => x, 5, 0.0, 5000.0) = 12500000.000000
quad (lam x => x, 5, 0.0, 6000.0) = 18000000.000000</pre>
=={{header|Axiom}}==
{{trans|Maxima}}
Axiom provides Legendre polynomials and related solvers.<
RECORD ==> Record(x : List Fraction Integer, w : List Fraction Integer)
Line 150 ⟶ 360:
c := (a+b)/2
h := (b-a)/2
h*reduce(+,[wi*subst(e,var=c+xi*h) for xi in u.x for wi in u.w])</
gaussIntegrate(4/(1+x^2), x=0..1, 20)
Line 157 ⟶ 367:
% - %pi
(2) - 0.3463549483_9378821092_475 E -26</
=={{header|C}}==
<
#include <math.h>
Line 243 ⟶ 453:
lege_inte(exp, -3, 3), exp(3) - exp(-3));
return 0;
}</
{{out}}
<pre>Roots: 0.90618 0.538469 0 -0.538469 -0.90618
Line 256 ⟶ 466:
Does not quite perform the task quite as specified since the node count, N, is set at compile time (to avoid heap allocation) so cannot be passed as a parameter.
<
#include <iomanip>
#include <cmath>
Line 395 ⟶ 605:
std::cout << "Integrating Exp(X) over [-3, 3]: " << gl5.integrate(-3., 3., RosettaExp) << std::endl;
std::cout << "Actual value: " << RosettaExp(3) - RosettaExp(-3) << std::endl;
}</
{{out}}
Line 404 ⟶ 614:
Actual value: 20.03574985
</pre>
=={{header|C sharp|C#}}==
Derived from the C++ and Java versions here.
<syntaxhighlight lang="csharp">
using System;
//Works in .NET 6+
//Tested using https://dotnetfiddle.net because im lazy
public class Program {
public static double[][] legeCoef(int N) {
//Initialising Jagged Array
double[][] lcoef = new double[N+1][];
for (int i=0; i < lcoef.Length; ++i)
lcoef[i] = new double[N+1];
lcoef[0][0] = lcoef[1][1] = 1;
for (int n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (int i = 1; i <= n; i++)
lcoef[n][i] = ((2*n - 1) * lcoef[n-1][i-1]
- (n-1) * lcoef[n-2][i] ) / n;
}
return lcoef;
}
static double legeEval(double[][] lcoef, int N, double x) {
double s = lcoef[N][N];
for (int i = N; i > 0; --i)
s = s * x + lcoef[N][i-1];
return s;
}
static double legeDiff(double[][] lcoef, int N, double x) {
return N * (x * legeEval(lcoef, N, x) - legeEval(lcoef, N-1, x)) / (x*x - 1);
}
static void legeRoots(double[][] lcoef, int N, out double[] lroots, out double[] weight) {
lroots = new double[N];
weight = new double[N];
double x, x1;
for (int i = 1; i <= N; i++) {
x = Math.Cos(Math.PI * (i - 0.25) / (N + 0.5));
do {
x1 = x;
x -= legeEval(lcoef, N, x) / legeDiff(lcoef, N, x);
}
while (x != x1);
lroots[i-1] = x;
x1 = legeDiff(lcoef, N, x);
weight[i-1] = 2 / ((1 - x*x) * x1*x1);
}
}
static double legeInte(Func<Double, Double> f, int N, double[] weights, double[] lroots, double a, double b) {
double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
for (int i = 0; i < N; i++)
sum += weights[i] * f.Invoke(c1 * lroots[i] + c2);
return c1 * sum;
}
//..................Main...............................
public static string Combine(double[] arrayD) {
return string.Join(", ", arrayD);
}
public static void Main() {
int N = 5;
var lcoeff = legeCoef(N);
double[] roots;
double[] weights;
legeRoots(lcoeff, N, out roots, out weights);
var integrateResult = legeInte(x=>Math.Exp(x), N, weights, roots, -3, 3);
Console.WriteLine("Roots: " + Combine(roots));
Console.WriteLine("Weights: " + Combine(weights)+ "\n" );
Console.WriteLine("integral: " + integrateResult );
Console.WriteLine("actual: " + (Math.Exp(3)-Math.Exp(-3)) );
}
}</syntaxhighlight>
{{out}}
<pre>
Roots: 0.906179845938664, 0.538469310105683, 0, -0.538469310105683, -0.906179845938664
Weights: 0.236926885056189, 0.478628670499367, 0.568888888888889, 0.478628670499367, 0.236926885056189
integral: 20.0355777183856
actual: 20.0357498548198
</pre>
=={{header|Common Lisp}}==
<
(defun guess (n i)
(cos (* pi
Line 468 ⟶ 780:
(funcall f (+ (* (/ (- b a) 2.0d0)
(aref x i))
(/ (+ a b) 2.0d0))))))))</
{{out|Example}}
<
#(0.906179845938664d0 0.5384693101056831d0 2.996272867003007d-95 -0.5384693101056831d0 -0.906179845938664d0)
Line 477 ⟶ 789:
(int #'exp 5 -3 3)
20.035577718385568d0</
Comparison of the 5-point rule with simpler, but more costly methods from the task [[Numerical Integration]]:
<
0.24999999999999997d0
Line 489 ⟶ 801:
(int #'(lambda (x) x) 5 0 6000)
1.8000000000000004d7</
=={{header|D}}==
{{trans|C}}
<
immutable struct GaussLegendreQuadrature(size_t N, FP=double,
Line 566 ⟶ 878:
writefln("Compred to actual: %10.12f",
3.0.exp - exp(-3.0));
}</
{{out}}
<pre>Roots: [0.90618, 0.538469, 0, -0.538469, -0.90618]
Line 575 ⟶ 887:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 668 ⟶ 980:
Writeln('Actual value: ',Exp(3)-Exp(-3):13:10);
Readln;
end.</
<pre>
Line 678 ⟶ 990:
=={{header|Fortran}}==
<
! -assume realloc_lhs
! when compiled with Intel Fortran.
Line 729 ⟶ 1,041:
end function
end program
</syntaxhighlight>
<pre>
Line 755 ⟶ 1,067:
20 20.0357498548198037979491872388495 -.82E-28
</pre>
=={{header|FreeBASIC}}==
{{trans|Wren}}
<syntaxhighlight lang="vbnet">#define PI 4 * Atn(1)
Const As Double LIM = 5
Dim Shared As Double lroots(LIM - 1)
Dim Shared As Double weight(LIM - 1)
Dim Shared As Double lcoef(LIM, LIM)
For i As Integer = 0 To LIM
For j As Integer = 0 To LIM
lcoef(i, j) = 0
Next j
Next i
Sub legeCoef()
lcoef(0, 0) = 1
lcoef(1, 1) = 1
For n As Integer = 2 To LIM
lcoef(n, 0) = -(n - 1) * lcoef(n - 2, 0) / n
For i As Integer = 1 To n
lcoef(n, i) = ((2 * n - 1) * lcoef(n - 1, i - 1) - (n - 1) * lcoef(n - 2, i)) / n
Next i
Next n
End Sub
Function legeEval(n As Integer, x As Double) As Double
Dim As Double s = lcoef(n, n)
For i As Integer = n To 1 Step -1
s = s * x + lcoef(n, i - 1)
Next i
Return s
End Function
Function legeDiff(n As Integer, x As Double) As Double
Return n * (x * legeEval(n, x) - legeEval(n - 1, x)) / (x * x - 1)
End Function
Sub legeRoots()
Dim As Double x = 0
Dim As Double x1 = 0
For i As Integer = 1 To LIM
x = Cos(PI * (i - 0.25) / (LIM + 0.5))
Do
x1 = x
x = x - legeEval(LIM, x) / legeDiff(LIM, x)
Loop Until x = x1
lroots(i - 1) = x
x1 = legeDiff(LIM, x)
weight(i - 1) = 2 / ((1 - x * x) * x1 * x1)
Next i
End Sub
Function legeIntegrate(f As Function (As Double) As Double, a As Double, b As Double) As Double
Dim As Double c1 = (b - a) / 2
Dim As Double c2 = (b + a) / 2
Dim As Double sum = 0
For i As Integer = 0 To LIM - 1
sum = sum + weight(i) * f(c1 * lroots(i) + c2)
Next i
Return c1 * sum
End Function
legeCoef()
legeRoots()
Print "Roots: ";
For i As Integer = 0 To LIM - 1
Print Using " ##.######"; lroots(i);
Next i
Print
Print "Weight:";
For i As Integer = 0 To LIM - 1
Print Using " ##.######"; weight(i);
Next i
Print
Function f(x As Double) As Double
Return Exp(x)
End Function
Dim As Double actual = Exp(3) - Exp(-3)
Print Using !"Integrating exp(x) over [-3, 3]:\n\t########.######,\ncompared to actual\n\t########.######"; legeIntegrate(@f, -3, 3); actual
Sleep</syntaxhighlight>
{{out}}
<pre>Roots: 0.906180 0.538469 0.000000 -0.538469 -0.906180
Weight: 0.236927 0.478629 0.568889 0.478629 0.236927
Integrating exp(x) over [-3, 3]:
20.035578,
compared to actual
20.035750</pre>
=={{header|Go}}==
Implementation pretty much by the methods given in the task description.
<
import (
Line 853 ⟶ 1,259:
}
panic("no convergence")
}</
{{out}}
<pre>
Line 863 ⟶ 1,269:
=={{header|Haskell}}==
Integration formula
<
where d = (b - a)/2
m = (b + a)/2
w x = 2/(1-x^2)/(legendreP' n x)^2
roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n]
x0 i = cos (pi*(i-1/4)/(n+1/2))</
Calculation of Legendre polynomials
<
where go 0 p2 _ = p2
go 1 _ p1 = p1
go n p2 p1 = go (n-1) p1 $ ((2*n-1)*x*p1 - (n-1)*p2)/n
legendreP' n x = n/(x^2-1)*(x*legendreP n x - legendreP (n-1) x)</
Universal auxilary functions
<
fixedPoint f x | abs (fx - x) < 1e-15 = x
| otherwise = fixedPoint f fx
where fx = f x</
Integration on a given mesh using Gauss-Legendre quadrature:
<
integrate f (m:ms) = sum $ zipWith (gaussLegendre 5 f) (m:ms) ms</
{{out}}
Line 904 ⟶ 1,310:
=={{header|J}}==
'''Solution:'''
<
getLegendreCoeffs=: verb define M.
if. y<:1 do. 1 {.~ - y+1 return. end.
Line 920 ⟶ 1,326:
'nodes wgts'=. getGaussLegendrePoints x
-: (-~/ y) * wgts +/@:* u -: nodes p.~ (+/ , -~/) y
)</
{{out|Example use}}
<
20.0356
-~/ ^ _3 3 NB. true value
20.0357</
=={{header|Java}}==
{{trans|C}}
{{works with|Java|8}}
<
import java.util.function.Function;
Line 1,004 ⟶ 1,410:
legeInte(x -> exp(x), -3, 3), exp(3) - exp(-3));
}
}</
<pre>Roots: 0,906180 0,538469 0,000000 -0,538469 -0,906180
Weight: 0,236927 0,478629 0,568889 0,478629 0,236927
Line 1,013 ⟶ 1,419:
=={{header|JavaScript}}==
<
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
const M = n => (n - (n % 2 !== 0)) / 2;
Line 1,033 ⟶ 1,439:
}
console.log(gaussLegendre(x => Math.exp(x), -3, 3, 5));
</syntaxhighlight>
{{output}}
<pre>
20.035577718385575
</pre>
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq'''
<syntaxhighlight lang=jq>
# output: an array
def legendreCoef($N):
{lcoef: (reduce range(0;$N+1) as $i (null; .[$i] = [range(0;$N + 1)| 0]))}
| .lcoef[0][0] = 1
| .lcoef[1][1] = 1
| reduce range(2; $N+1) as $n (.;
.lcoef[$n][0] = -($n-1) * .lcoef[$n -2][0] / $n
| reduce range (1; $n+1) as $i (.;
.lcoef[$n][$i] = ((2*$n - 1) * .lcoef[$n-1][$i-1] - ($n - 1) * .lcoef[$n-2][$i]) / $n ) )
| .lcoef ;
# input: lcoef
# output: the value
def legendreEval($n; $x):
. as $lcoef
| reduce range($n; 0 ;-1) as $i ( $lcoef[$n][$n] ; . * $x + $lcoef[$n][$i-1] ) ;
# input: lcoef
def legendreDiff($n; $x):
$n * ($x * legendreEval($n; $x) - legendreEval($n-1; $x)) / ($x*$x - 1) ;
# input: lcoef
# output: {lroots, weight}
def legendreRoots($N):
def pi: 1|atan * 4;
. as $lcoef
| { x: 0, x1: null}
| reduce range(1; 1+$N) as $i (.;
.x = ((pi * ($i - 0.25) / ($N + 0.5)) | cos )
| until (.x == .x1;
.x1 = .x
| .x as $x
| .x = .x - ($lcoef | (legendreEval($N; $x) / legendreDiff($N; $x) )) )
| .lroots[$i-1] = .x
| .x as $x
| .x1 = ($lcoef|legendreDiff($N; $x))
| .weight[$i-1] = 2 / ((1 - .x*.x) * .x1 * .x1) ) ;
# Input: {lroots, weight}
def legendreIntegrate(f; $a; $b; $N):
.lroots as $lroots
| .weight as $weight
| (($b - $a) / 2) as $c1
| (($b + $a) / 2) as $c2
| reduce range(0;$N) as $i (0; . + $weight[$i] * (($c1* $lroots[$i] + $c2)|f) )
| $c1 * .;
def task($N):
def actual: 3|exp - ((-3)|exp);
legendreCoef($N)
| legendreRoots($N)
| "Roots: ",
.lroots,
"\nWeight:",
.weight,
"\nIntegrating exp(x) over [-3, 3]: \(legendreIntegrate(exp; -3; 3; N))",
"compared to actual: \(actual)" ;
task(5)
</syntaxhighlight>
'''Invocation:'''
<pre>
jq -ncr -f gauss-legendre-quadrature.jq
</pre>
{{output}}
<pre>
Roots:
[0.906179845938664,0.5384693101056831,0,-0.5384693101056831,-0.906179845938664]
Weight:
[0.23692688505618922,0.4786286704993667,0.5688888888888889,0.4786286704993667,0.23692688505618922]
Integrating exp(x) over [-3, 3]: 20.035577718385575
compared to actual: 20.035749854819805
</pre>
=={{header|Julia}}==
This function computes the points and weights of an ''N''-point Gauss–Legendre quadrature rule on the interval (''a'',''b''). It uses the O(''N''<sup>2</sup>) algorithm described in Trefethen & Bau, ''Numerical Linear Algebra'', which finds the points and weights by computing the eigenvalues and eigenvectors of a real-symmetric tridiagonal matrix:
<
function gauss(a, b, N)
λ, Q = eigen(SymTridiagonal(zeros(N), [n / sqrt(4n^2 - 1) for n = 1:N-1]))
@. (λ + 1) * (b - a) / 2 + a, [2Q[1, i]^2 for i = 1:N] * (b - a) / 2
end</
(This code is a simplified version of the <code>Base.gauss</code> subroutine in the Julia standard library.)
{{out}}
Line 1,059 ⟶ 1,548:
=={{header|Kotlin}}==
{{trans|Java}}
<
class Legendre(val N: Int) {
Line 1,116 ⟶ 1,605:
println("compared to actual:")
println("\t%10.8f".format(exp(3.0) - exp(-3.0)))
}</
{{Out}}
<pre>Roots: 0.906180 0.538469 0.000000 -0.538469 -0.906180
Line 1,126 ⟶ 1,615:
=={{header|Lua}}==
<
local legendreRoots = {}
Line 1,194 ⟶ 1,683:
do
print(gaussLegendreQuadrature(function(x) return math.exp(x) end, -3, 3, 5))
end</
{{out}}<pre>20.035577718386</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
code assumes function to be integrated has attribute Listable which is true of most built in Mathematica functions
<
Block[{nodes, x, weights},
nodes = Cases[NSolve[LegendreP[degree, x] == 0, x], _?NumericQ, Infinity];
weights = 2 (1 - nodes^2)/(degree LegendreP[degree - 1, nodes])^2;
(b - a)/2 weights.func[(b - a)/2 nodes + (b + a)/2]]
gaussLegendreQuadrature[Exp, {-3, 3}]</
{{out}}<pre>20.0356</pre>
=={{header|MATLAB}}==
Translated from the Python solution.
<syntaxhighlight lang="matlab">
%Print the result.
disp(GLGD_int(@(x) exp(x), -3, 3, 5));
Line 1,287 ⟶ 1,776:
end
end
</syntaxhighlight>
{{out}}<pre>20.0356</pre>
=={{header|Maxima}}==
<
p: expand(legendre_p(n, x)),
q: expand(n/2*diff(p, x)*legendre_p(n - 1, x)),
Line 1,321 ⟶ 1,810:
% - bfloat(integrate(exp(x), x, -3, 3));
/* -1.721364342416440206515136565621888185351b-4 */</
=={{header|Nim}}==
{{trans|Common Lisp}}
<
import math, strformat
Line 1,404 ⟶ 1,893:
main()
</syntaxhighlight>
{{out}}
<pre>
Line 1,413 ⟶ 1,902:
=={{header|OCaml}}==
<
| 0 -> 1.0
| 1 -> x
Line 1,448 ⟶ 1,937:
let f1 x = f ((x*.(b-.a) +. a +. b)*.0.5) in
let eval s (x,w) = s +. w*.(f1 x) in
0.5*.(b-.a)*.(List.fold_left eval 0.0 (nodes n));;</
which can be used in:
<
Printf.printf
"Gauss-Legendre %2d-point quadrature for exp over [-3..3] = %.16f\n"
Line 1,458 ⟶ 1,947:
calc 10;;
calc 15;;
calc 20;;</
{{out}}
<pre>
Line 1,467 ⟶ 1,956:
</pre>
This shows convergence to the correct double-precision value of the integral
<
20.0357498548198052</
although going beyond 20 points starts reducing the accuracy, due to accumulated rounding errors.
=={{header|ooRexx}}==
<
* 31.10.2013 Walter Pachl Translation from REXX (from PL/I)
* using ooRexx' rxmath package
Line 1,541 ⟶ 2,030:
Return
::requires 'rxmath' LIBRARY</
Output:
<pre> 1 6.0000000000000000000000000000000000000000 -1.4036E+1
Line 1,568 ⟶ 2,057:
{{works with|PARI/GP|2.4.2 and above}}
This task is easy in GP thanks to built-in support for Legendre polynomials and efficient (Schonhage-Gourdon) polynomial root finding.
<
my(P=pollegendre(n),Pp=P',x=polroots(P));
(b-a)*sum(i=1,n,f((b-a)*x[i]/2+(a+b)/2)/(1-x[i]^2)/subst(Pp,'x,x[i])^2)
};
# \\ Turn on timer
GLq(x->exp(x), -3, 3, 5) \\ As of version 2.4.4, this can be written GLq(exp, -3, 3, 5)</
{{out}}
<pre>time = 0 ms.
Line 1,580 ⟶ 2,069:
{{works with|PARI/GP|2.9.0 and above}}
Gauss-Legendre quadrature is built-in from 2.9 forward.
<
intnumgauss(x=-3, 3, exp(x)) \\ determine number of points automatically; all digits shown should be accurate</
{{out}}
<pre>%1 = 20.035746975092343883065457558549925374
Line 1,590 ⟶ 2,079:
{{works with|Free Pascal|3.0.4}}
{{works with|Multics Pascal|8.0.4a}}
<
const Order = 5;
Line 1,685 ⟶ 2,174:
Writeln('Integrating Exp(x) over [-3, 3]: ',LegInt(-3,3):13:10);
Writeln('Actual value: ',Exp(3)-Exp(-3):13:10);
end.</
{{out}}
<pre>
Line 1,696 ⟶ 2,185:
=={{header|Perl}}==
{{trans|Raku}}
<
use constant pi => 3.14159265;
Line 1,765 ⟶ 2,254:
printf("Gauss-Legendre %2d-point quadrature ∫₋₃⁺³ exp(x) dx ≈ %.13f\n", $_, quadrature($_, -3, +3) )
for 5 .. 10, 20;
</syntaxhighlight>
{{out}}
<pre>Gauss-Legendre 5-point quadrature ∫₋₃⁺³ exp(x) dx ≈ 20.0355777183856
Line 1,777 ⟶ 2,266:
=={{header|Phix}}==
{{trans|Lua}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">order</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">legendreRoots</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
<span style="color: #000000;">legendreWeights</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">z</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">((</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">term</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">z</span><span style="color: #0000FF;">*</span><span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)-(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">))/</span><span style="color: #000000;">term</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">legendreDerivative</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">term</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">*</span><span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #000000;">term</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)))/(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">*</span><span style="color: #000000;">z</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">getLegendreRoots</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">legendreRoots</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">index</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">order</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">index</span><span style="color: #0000FF;">-</span><span style="color: #000000;">0.25</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">order</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">legendre</span><span style="color: #0000FF;">(</span><span style="color: #000000;">order</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">legendreDerivative</span><span style="color: #0000FF;">(</span><span style="color: #000000;">order</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">2e-16</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">legendreRoots</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">y</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">getLegendreWeights</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">legendreWeights</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">index</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">order</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">lri</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">legendreRoots</span><span style="color: #0000FF;">[</span><span style="color: #000000;">index</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">diff</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">legendreDerivative</span><span style="color: #0000FF;">(</span><span style="color: #000000;">order</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lri</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">weight</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span> <span style="color: #0000FF;">/</span> <span style="color: #0000FF;">((</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lri</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">diff</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">legendreWeights</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">weight</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">gaussLegendreQuadrature</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lowerLimit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">upperLimit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">order</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">getLegendreRoots</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">getLegendreWeights</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">c1</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">upperLimit</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">lowerLimit</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">2</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">c2</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">upperLimit</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">lowerLimit</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">2</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">order</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">legendreWeights</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c1</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">legendreRoots</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">c2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">c1</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">machine_bits</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">32</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"%.13f"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"%.14f"</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span> <span style="color: #008080;">to</span> <span style="color: #000000;">11</span> <span style="color: #008080;">by</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">gaussLegendreQuadrature</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">exp</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"roots:"</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">legendreRoots</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"weights:"</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">legendreWeights</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Gauss-Legendre %2d-point quadrature for exp over [-3..3] = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">order</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">exp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)-</span><span style="color: #7060A8;">exp</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" compared to actual = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,868 ⟶ 2,356:
=={{header|PL/I}}==
Translated from Fortran.
<
Integration_Gauss: procedure options (main);
Line 1,922 ⟶ 2,410:
end gaussquad;
end Integration_Gauss;
</syntaxhighlight>
<pre>
1 6.0000000000000000 -1.40E+0001
Line 1,951 ⟶ 2,439:
=={{header|Python}}==
{{libheader|NumPy}}
<
##################################################################
Line 2,047 ⟶ 2,535:
print "Integral : ", ans
else:
print "Integral evaluation failed"</
{{out}}
<pre>
Line 2,055 ⟶ 2,543:
Integral : 20.0355777184
</pre>
===With library routine===
One can also use the already invented wheel in NumPy:
<syntaxhighlight lang="python">import numpy as np
# func is a function that takes a list-like input values
def gauss_legendre_integrate(func, domain, deg):
x, w = np.polynomial.legendre.leggauss(deg)
s = (domain[1] - domain[0])/2
a = (domain[1] + domain[0])/2
return np.sum(s*w*func(s*x + a))
for d in range(3, 10):
print(d, gauss_legendre_integrate(np.exp, [-3, 3], d))</syntaxhighlight>
{{out}}
<pre>3 19.853691996805587
4 20.028688395290693
5 20.035577718385575
6 20.035746975092323
7 20.03574981972664
8 20.035749854494522
9 20.03574985481744</pre>
=={{header|Racket}}==
Line 2,060 ⟶ 2,569:
Computation of the Legendre polynomials and derivatives:
<
(define (LegendreP n x)
(let compute ([n n] [Pn-1 x] [Pn-2 1])
Line 2,075 ⟶ 2,584:
(- (* x (LegendreP n x))
(LegendreP (- n 1) x))))
</syntaxhighlight>
Computation of the Legendre polynomial roots:
<
(define (LegendreP-root n i)
; newton-raphson step
Line 2,093 ⟶ 2,602:
x′
(next (newton-step x′) x′)))))
</syntaxhighlight>
Computation of Gauss-Legendre nodes and weights
<
(define (Gauss-Legendre-quadrature n)
;; positive roots
Line 2,114 ⟶ 2,623:
(if (odd? n) (list (/ 2 (sqr (LegendreP′ n 0)))) '())
(reverse weights))))
</syntaxhighlight>
Integration using Gauss-Legendre quadratures:
<
(define (integrate f a b #:nodes (n 5))
(define m (/ (+ a b) 2))
Line 2,125 ⟶ 2,634:
(define (g x) (f (+ m (* d x))))
(* d (+ (apply + (map * w (map g x))))))
</syntaxhighlight>
Usage:
<
> (Gauss-Legendre-quadrature 5)
'(-0.906179845938664 -0.5384693101056831 0 0.5384693101056831 0.906179845938664)
Line 2,139 ⟶ 2,648:
> (- (exp 3) (exp -3)
20.035749854819805
</syntaxhighlight>
Accuracy of the method:
<
> (require plot)
> (parameterize ([plot-x-label "Number of Gaussian nodes"]
Line 2,152 ⟶ 2,661:
(list n (abs (- (integrate exp -3 3 #:nodes n)
(- (exp 3) (exp -3)))))))))
</syntaxhighlight>
[[File:gauss.png]]
Line 2,165 ⟶ 2,674:
Note: The calculations of Pn(x) and P'n(x) could be combined to further reduce duplicated effort. We also could cache P'n(x) from the last Newton-Raphson step for the weight calculation.
<syntaxhighlight lang="raku"
multi legendre-pair(Int $n, $x) {
my ($m1, $m2) = legendre-pair($n - 1, $x);
Line 2,219 ⟶ 2,728:
say "Gauss-Legendre $_.fmt('%2d')-point quadrature ∫₋₃⁺³ exp(x) dx ≈ ",
quadrature($_, &exp, -3, +3) for flat 5 .. 10, 20;</
{{out}}
Line 2,232 ⟶ 2,741:
=={{header|REXX}}==
===version 1===
<
* 31.10.2013 Walter Pachl Translation from PL/I
* 01.11.2014 -"- see Version 2 for improvements
Line 2,345 ⟶ 2,854:
End
Numeric Digits (prec)
Return r+0</
Output:
<pre> 1 6.0000000000000000000000000000000000000000 -1.4036E+1
Line 2,397 ⟶ 2,906:
<br>where there's practically no space on the right side of the REXX source statements. It presents a good
<br>visual indication of what's what, but it's the dickens to pay when updating the source code.
<
pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2
Line 2,445 ⟶ 2,954:
/*───────────────────────────────────────────────────────────────────────────────────────────*/
exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1
_=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,492 ⟶ 3,001:
It is about twice as slow as version 2, due to the doubling of the number of decimal digits (precision).
<
pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2
!.= .; b= 3; a= -b; bma= b - a; bmaH= bma / 2; tiny= '1e-'digs
Line 2,542 ⟶ 3,051:
/*───────────────────────────────────────────────────────────────────────────────────────────*/
exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1
_=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix</
{{out|output|text= when using the default inputs:}}
Line 2,612 ⟶ 3,121:
=={{header|Scala}}==
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/rrvzhH1/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/yYqRqizfSZip2DhYbdfZ2w Scastie (remote JVM)].
<
object GaussLegendreQuadrature extends App {
Line 2,660 ⟶ 3,169:
println(f"compared to actual%n\t${exp(3) - exp(-3)}%10.8f")
}</
=={{header|Sidef}}==
{{trans|Raku}}
<
func legendre_pair( n, x) {
var (m1, m2) = legendre_pair(n - 1, x)
Line 2,723 ⟶ 3,232:
printf("Gauss-Legendre %2d-point quadrature ∫₋₃⁺³ exp(x) dx ≈ %.15f\n",
i, quadrature(i, {.exp}, -3, +3))
}</
{{out}}
<pre>Gauss-Legendre 5-point quadrature ∫₋₃⁺³ exp(x) dx ≈ 20.035577718385561
Line 2,738 ⟶ 3,247:
{{tcllib|math::polynomials}}
{{tcllib|math::special}}
<
package require math::special
package require math::polynomials
Line 2,800 ⟶ 3,309:
}
expr {$sum * $rangesize2}
}</
Demonstrating:
<
puts "weights(5) = [weights [nodes 5]]"
set exp {x {expr {exp($x)}}}
puts "int(exp,-3,3) = [gausslegendreintegrate $exp 5 -3 3]"</
{{out}}
<pre>
Line 2,815 ⟶ 3,324:
=={{header|Ursala}}==
using arbitrary precision arithmetic
<
#import nat
Line 2,848 ⟶ 3,357:
mp..shrink^/~& difference\"p"+ mp..prec,
mp..mul^|/~& mp..add:-0E0+ * mp..mul^/~&rr ^H/~&ll mp..add^\~&lrr mp..mul@lrPrXl,
^(~&rl,-*nodes("p","n"))^|/~& mp..vid~~G/2E0+ ^/mp..bus mp..add+-</
demonstration program:<
demo =
Line 2,855 ⟶ 3,364:
~&lNrCT (
^|lNrCT(:/'nodes:',:/'weights:')@lSrSX ..mp2str~~* nodes/160 5,
:/'integral:' ~&iNC ..mp2str integral(160,5) (mp..exp,-3E0,3E0))</
{{out}}
<pre>
Line 2,878 ⟶ 3,387:
{{trans|C}}
{{libheader|Wren-fmt}}
<
var N = 5
Line 2,938 ⟶ 3,447:
var actual = 3.exp - (-3).exp
Fmt.print("\nIntegrating exp(x) over [-3, 3]:\n\t$10.8f,\n" +
"compared to actual\n\t$10.8f", legeIntegrate.call(f, -3, 3), actual)</
{{out}}
Line 2,952 ⟶ 3,461:
=={{header|zkl}}==
{{trans|Raku}}
<
if(n==1) return(x,1.0);
m1,m2:=legendrePair(n-1,x);
Line 2,996 ⟶ 3,505:
scale:='wrap(x){ (x*(b - a) + a + b) / 2 };
nds.reduce('wrap(p,[(r,w)]){ p + w*f(scale(r)) },0.0) * (b - a)/2
}</
<
("Gauss-Legendre %2d-point quadrature "
"\U222B;\U208B;\U2083;\U207A;\UB3; exp(x) dx = %.13f")
.fmt(n,quadrature(n, fcn(x){ x.exp() }, -3, 3))
})</
{{out}}
<pre>
|