Numerical integration/Gauss-Legendre Quadrature: Difference between revisions

Added FreeBASIC
(→‎{{header|Wren}}: Now uses new core library method.)
(Added FreeBASIC)
 
(9 intermediate revisions by 7 users not shown)
Line 51:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F legendreIn(x, n)
F prev1(idx, pn1)
R (2 * idx - 1) * @x * pn1
Line 120:
R result * sum
 
print(‘integral: ’integ(x -> exp(x), 5, -3, 3))</langsyntaxhighlight>
 
{{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.<langsyntaxhighlight Axiomlang="axiom">NNI ==> NonNegativeInteger
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])</langsyntaxhighlight>Example:<syntaxhighlight lang Axiom="axiom">digits(50)
gaussIntegrate(4/(1+x^2), x=0..1, 20)
 
Line 157 ⟶ 367:
% - %pi
 
(2) - 0.3463549483_9378821092_475 E -26</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <math.h>
 
Line 243 ⟶ 453:
lege_inte(exp, -3, 3), exp(3) - exp(-3));
return 0;
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="cpp">#include <iostream>
#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;
}</langsyntaxhighlight>
 
{{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}}==
<langsyntaxhighlight lang="lisp">;; Computes the initial guess for the root i of a n-order Legendre polynomial.
(defun guess (n i)
(cos (* pi
Line 468 ⟶ 780:
(funcall f (+ (* (/ (- b a) 2.0d0)
(aref x i))
(/ (+ a b) 2.0d0))))))))</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="lisp">(nodes 5)
#(0.906179845938664d0 0.5384693101056831d0 2.996272867003007d-95 -0.5384693101056831d0 -0.906179845938664d0)
 
Line 477 ⟶ 789:
 
(int #'exp 5 -3 3)
20.035577718385568d0</langsyntaxhighlight>
Comparison of the 5-point rule with simpler, but more costly methods from the task [[Numerical Integration]]:
<langsyntaxhighlight lang="lisp">(int #'(lambda (x) (expt x 3)) 5 0 1)
0.24999999999999997d0
 
Line 489 ⟶ 801:
 
(int #'(lambda (x) x) 5 0 6000)
1.8000000000000004d7</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.math;
 
immutable struct GaussLegendreQuadrature(size_t N, FP=double,
Line 566 ⟶ 878:
writefln("Compred to actual: %10.12f",
3.0.exp - exp(-3.0));
}</langsyntaxhighlight>
{{out}}
<pre>Roots: [0.90618, 0.538469, 0, -0.538469, -0.90618]
Line 575 ⟶ 887:
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">program Legendre;
 
{$APPTYPE CONSOLE}
Line 668 ⟶ 980:
Writeln('Actual value: ',Exp(3)-Exp(-3):13:10);
Readln;
end.</langsyntaxhighlight>
 
<pre>
Line 678 ⟶ 990:
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">! Works with gfortran but needs the option
! -assume realloc_lhs
! when compiled with Intel Fortran.
Line 729 ⟶ 1,041:
end function
end program
</syntaxhighlight>
</lang>
 
<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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 853 ⟶ 1,259:
}
panic("no convergence")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 863 ⟶ 1,269:
=={{header|Haskell}}==
Integration formula
<langsyntaxhighlight lang="haskell">gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ]
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))</langsyntaxhighlight>
 
Calculation of Legendre polynomials
<langsyntaxhighlight lang="haskell">legendreP n x = go n 1 x
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)</langsyntaxhighlight>
 
Universal auxilary functions
<langsyntaxhighlight lang="haskell">findRoot f df = fixedPoint (\x -> x - f x / df x)
 
fixedPoint f x | abs (fx - x) < 1e-15 = x
| otherwise = fixedPoint f fx
where fx = f x</langsyntaxhighlight>
 
Integration on a given mesh using Gauss-Legendre quadrature:
<langsyntaxhighlight lang="haskell">integrate _ [] = 0
integrate f (m:ms) = sum $ zipWith (gaussLegendre 5 f) (m:ms) ms</langsyntaxhighlight>
 
{{out}}
Line 904 ⟶ 1,310:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">NB. returns coefficents for yth-order Legendre polynomial
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
)</langsyntaxhighlight>
{{out|Example use}}
<langsyntaxhighlight lang="j"> 5 ^ integrateGaussLegendre _3 3
20.0356
-~/ ^ _3 3 NB. true value
20.0357</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|C}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.Math.*;
import java.util.function.Function;
 
Line 1,004 ⟶ 1,410:
legeInte(x -> exp(x), -3, 3), exp(3) - exp(-3));
}
}</langsyntaxhighlight>
<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}}==
<langsyntaxhighlight lang="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>
</lang>
{{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:
<langsyntaxhighlight lang="julia">using LinearAlgebra
 
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</langsyntaxhighlight>
(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}}
<langsyntaxhighlight lang="scala">import java.lang.Math.*
 
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)))
}</langsyntaxhighlight>
{{Out}}
<pre>Roots: 0.906180 0.538469 0.000000 -0.538469 -0.906180
Line 1,126 ⟶ 1,615:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">local order = 0
 
local legendreRoots = {}
Line 1,194 ⟶ 1,683:
do
print(gaussLegendreQuadrature(function(x) return math.exp(x) end, -3, 3, 5))
end</langsyntaxhighlight>
{{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
<langsyntaxhighlight Mathematicalang="mathematica">gaussLegendreQuadrature[func_, {a_, b_}, degree_: 5] :=
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}]</langsyntaxhighlight>
{{out}}<pre>20.0356</pre>
 
=={{header|MATLAB}}==
Translated from the Python solution.
<syntaxhighlight lang="matlab">
<lang MATLAB>
%Print the result.
disp(GLGD_int(@(x) exp(x), -3, 3, 5));
Line 1,287 ⟶ 1,776:
end
end
</syntaxhighlight>
</lang>
{{out}}<pre>20.0356</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">gauss_coeff(n) := block([p, q, v, w],
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 */</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang="nim">
import math, strformat
 
Line 1,404 ⟶ 1,893:
 
main()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,413 ⟶ 1,902:
 
=={{header|OCaml}}==
<langsyntaxhighlight OCamllang="ocaml">let rec leg n x = match n with (* Evaluate Legendre polynomial *)
| 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));;</langsyntaxhighlight>
which can be used in:
<langsyntaxhighlight OCamllang="ocaml">let calc n =
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;;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,467 ⟶ 1,956:
</pre>
This shows convergence to the correct double-precision value of the integral
<langsyntaxhighlight Ocamllang="ocaml">Printf.printf "%.16f\n" ((exp 3.0) -.(exp (-3.0)));;
20.0357498548198052</langsyntaxhighlight>
although going beyond 20 points starts reducing the accuracy, due to accumulated rounding errors.
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="parigp">GLq(f,a,b,n)={
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)</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="parigp">intnumgauss(x=-3, 3, exp(x), intnumgaussinit(5))
intnumgauss(x=-3, 3, exp(x)) \\ determine number of points automatically; all digits shown should be accurate</langsyntaxhighlight>
{{out}}
<pre>%1 = 20.035746975092343883065457558549925374
Line 1,590 ⟶ 2,079:
{{works with|Free Pascal|3.0.4}}
{{works with|Multics Pascal|8.0.4a}}
<langsyntaxhighlight Pascallang="pascal">program Legendre(output);
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.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,696 ⟶ 2,185:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(sum);
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>
</lang>
{{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)-->
<lang Phix>integer order = 0
<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>
sequence legendreRoots = {},
legendreWeights = {}
<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>
function legendre(integer term, atom z)
if term=0 then
<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>
return 1
<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>
elsif term=1 then
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
return z
<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>
else
<span style="color: #008080;">return</span> <span style="color: #000000;">z</span>
return ((2*term-1)*z*legendre(term-1,z)-(term-1)*legendre(term-2,z))/term
<span style="color: #008080;">else</span>
end if
<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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function legendreDerivative(integer term, atom z)
if term=0
<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>
or term=1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">term</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
return term
<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>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">term</span>
return (term*(z*legendre(term,z)-legendre(term-1,z)))/(z*z-1)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<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>
procedure getLegendreRoots()
legendreRoots = {}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">getLegendreRoots</span><span style="color: #0000FF;">()</span>
for index=1 to order do
<span style="color: #000000;">legendreRoots</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
atom y = cos(PI*(index-0.25)/(order+0.5))
<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>
while 1 do
<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>
atom y1 = y
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
y -= legendre(order,y)/legendreDerivative(order,y)
<span style="color: #004080;">atom</span> <span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y</span>
if abs(y-y1)<2e-16 then exit end if
<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>
end while
<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>
legendreRoots &= y
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #000000;">legendreRoots</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">y</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure getLegendreWeights()
legendreWeights = {}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">getLegendreWeights</span><span style="color: #0000FF;">()</span>
for index=1 to order do
<span style="color: #000000;">legendreWeights</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
atom lri = legendreRoots[index],
<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>
diff = legendreDerivative(order,lri),
<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>
weight = 2 / ((1-power(lri,2))*power(diff,2))
<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>
legendreWeights &= weight
<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>
end for
<span style="color: #000000;">legendreWeights</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">weight</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
function gaussLegendreQuadrature(integer f, lowerLimit, upperLimit, n)
order = n
<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>
getLegendreRoots()
getLegendreWeights()
<span style="color: #000000;">getLegendreRoots</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">getLegendreWeights</span><span style="color: #0000FF;">()</span>
atom c1 = (upperLimit - lowerLimit) / 2
atom c2 = (upperLimit + lowerLimit) / 2
<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>
atom s = 0
<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>
for i = 1 to order do
s += legendreWeights[i] * call_func(f,{c1 * legendreRoots[i] + c2})
<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>
end for
<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>
return c1 * s
end function
<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>
include pmaths.e -- exp()
constant r_exp = routine_id("exp")
<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>
string fmt = iff(machine_bits()=32?"%.13f":"%.14f")
<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>
string res
<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>
for i=5 to 11 by 6 do
<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>
res = sprintf(fmt,{gaussLegendreQuadrature(r_exp, -3, 3, i)})
<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>
if i=5 then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
puts(1,"roots:") ?legendreRoots
<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>
puts(1,"weights:") ?legendreWeights
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<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>
printf(1,"Gauss-Legendre %2d-point quadrature for exp over [-3..3] = %s\n",{order,res})
<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>
end for
<!--</syntaxhighlight>-->
res = sprintf(fmt,{exp(3)-exp(-3)})
printf(1," compared to actual = %s\n",{res})</lang>
{{out}}
<pre>
Line 1,868 ⟶ 2,356:
=={{header|PL/I}}==
Translated from Fortran.
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange, size, fofl):
Integration_Gauss: procedure options (main);
 
Line 1,922 ⟶ 2,410:
end gaussquad;
end Integration_Gauss;
</syntaxhighlight>
</lang>
<pre>
1 6.0000000000000000 -1.40E+0001
Line 1,951 ⟶ 2,439:
=={{header|Python}}==
{{libheader|NumPy}}
<langsyntaxhighlight Pythonlang="python">from numpy import *
##################################################################
Line 2,047 ⟶ 2,535:
print "Integral : ", ans
else:
print "Integral evaluation failed"</langsyntaxhighlight>
{{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:
 
<langsyntaxhighlight lang="racket">
(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>
</lang>
 
Computation of the Legendre polynomial roots:
 
<langsyntaxhighlight lang="racket">
(define (LegendreP-root n i)
; newton-raphson step
Line 2,093 ⟶ 2,602:
x′
(next (newton-step x′) x′)))))
</syntaxhighlight>
</lang>
 
Computation of Gauss-Legendre nodes and weights
 
<langsyntaxhighlight lang="racket">
(define (Gauss-Legendre-quadrature n)
;; positive roots
Line 2,114 ⟶ 2,623:
(if (odd? n) (list (/ 2 (sqr (LegendreP′ n 0)))) '())
(reverse weights))))
</syntaxhighlight>
</lang>
 
Integration using Gauss-Legendre quadratures:
 
<langsyntaxhighlight lang="racket">
(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>
</lang>
 
Usage:
 
<langsyntaxhighlight lang="racket">
> (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>
</lang>
 
Accuracy of the method:
 
<langsyntaxhighlight lang="racket">
> (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>
</lang>
[[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" perl6line>multi legendre-pair( 1 , $x) { $x, 1 }
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;</langsyntaxhighlight>
 
{{out}}
Line 2,232 ⟶ 2,741:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*---------------------------------------------------------------------
* 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</langsyntaxhighlight>
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. &nbsp; It presents a good
<br>visual indication of what's what, &nbsp; but it's the dickens to pay when updating the source code.
<langsyntaxhighlight lang="rexx">/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,492 ⟶ 3,001:
 
It is about twice as slow as version 2, &nbsp; due to the doubling of the number of decimal digits &nbsp; (precision).
<langsyntaxhighlight lang="rexx">/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */
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</langsyntaxhighlight>
{{out|output|text=&nbsp; 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)].
<langsyntaxhighlight Scalalang="scala">import scala.math.{Pi, cos, exp}
 
object GaussLegendreQuadrature extends App {
Line 2,660 ⟶ 3,169:
println(f"compared to actual%n\t${exp(3) - exp(-3)}%10.8f")
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func legendre_pair((1), x) { (x, 1) }
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))
}</langsyntaxhighlight>
{{out}}
<pre>Gauss-Legendre 5-point quadrature ∫₋₃⁺³ exp(x) dx ≈ 20.035577718385561
Line 2,738 ⟶ 3,247:
{{tcllib|math::polynomials}}
{{tcllib|math::special}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require math::special
package require math::polynomials
Line 2,800 ⟶ 3,309:
}
expr {$sum * $rangesize2}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "nodes(5) = [nodes 5]"
puts "weights(5) = [weights [nodes 5]]"
set exp {x {expr {exp($x)}}}
puts "int(exp,-3,3) = [gausslegendreintegrate $exp 5 -3 3]"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,815 ⟶ 3,324:
=={{header|Ursala}}==
using arbitrary precision arithmetic
<langsyntaxhighlight Ursalalang="ursala">#import std
#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+-</langsyntaxhighlight>
demonstration program:<langsyntaxhighlight Ursalalang="ursala">#show+
 
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))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,878 ⟶ 3,387:
{{trans|C}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for 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)</langsyntaxhighlight>
 
{{out}}
Line 2,952 ⟶ 3,461:
=={{header|zkl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="zkl">fcn legendrePair(n,x){ //-->(float,float)
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
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">[5..10].walk().append(20).pump(Console.println,fcn(n){
("Gauss-Legendre %2d-point quadrature "
"\U222B;\U208B;\U2083;\U207A;\UB3; exp(x) dx = %.13f")
.fmt(n,quadrature(n, fcn(x){ x.exp() }, -3, 3))
})</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits