Numerical integration/Adaptive Simpson's method: Difference between revisions
Content added Content deleted
(Added Prolog ahead of →{{header|Python}}) |
|||
Line 1,340: | Line 1,340: | ||
Simpson's integration of sine from 0 to 1 = 0.459698 |
Simpson's integration of sine from 0 to 1 = 0.459698 |
||
</pre> |
</pre> |
||
=={{header|Python}}== |
|||
{{works with|SWI-Prolog|9.1.2}} |
|||
{{works with|GNU Prolog|1.5.0}} |
|||
<syntaxhighlight lang="prolog"> |
|||
%%% -*- mode: prolog; prolog-indent-width: 2; -*- |
|||
main :- |
|||
quad_asr(sine, 0.0, 1.0, 0.000000001, 1, QuadVal), |
|||
write('estimate of ∫ sin x dx from 0 to 1: '), |
|||
write(QuadVal), |
|||
write('\n'), |
|||
halt. |
|||
sine(X, Y) :- Y is sin(X). |
|||
quad_asr(F, A, B, Tol, Depth, QuadVal) :- |
|||
call(F, A, FA), |
|||
call(F, B, FB), |
|||
simpson_rule(F, A, FA, B, FB, M, FM, Whole), |
|||
recursive_simpson(F, A, FA, B, FB, Tol, Whole, M, FM, Depth, |
|||
QuadVal). |
|||
recursive_simpson(F, A, FA, B, FB, Tol, Whole, M, FM, Depth, |
|||
QuadVal) :- |
|||
simpson_rule(F, A, FA, M, FM, LM, FLM, Left), |
|||
simpson_rule(F, M, FM, B, FB, RM, FRM, Right), |
|||
Delta is (Left + Right - Whole), |
|||
Tol_ is (0.5 * Tol), |
|||
((Depth =< 0.0, Tol_ \= Tol, abs(Delta) =< 15.0 * Tol) |
|||
-> QuadVal is Left + Right + (Delta / 15.0) |
|||
; (Depth_ is Depth - 1, |
|||
recursive_simpson(F, A, FA, M, FM, Tol_, Left, LM, FLM, |
|||
Depth_, QuadValLeft), |
|||
recursive_simpson(F, M, FM, B, FB, Tol_, Right, RM, FRM, |
|||
Depth_, QuadValRight), |
|||
QuadVal is QuadValLeft + QuadValRight)). |
|||
simpson_rule(F, A, FA, B, FB, M, FM, QuadVal) :- |
|||
M is (0.5 * (A + B)), |
|||
call(F, M, FM), |
|||
QuadVal is ((B - A) / 6.0) * (FA + (4.0 * FM) + FB). |
|||
:- initialization(main). |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
The output varies by Prolog implementation: |
|||
<pre>$ swipl adaptive_simpson_task_prolog.pl |
|||
estimate of ∫ sin x dx from 0 to 1: 0.4596976941317858 |
|||
$ gplc adaptive_simpson_task_prolog.pl && ./adaptive_simpson_task_prolog |
|||
estimate of ∫ sin x dx from 0 to 1: 0.45969769413178579</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |