Sum of a series: Difference between revisions
(Sum of a series en BASIC256) |
Langurmonkey (talk | contribs) |
||
(40 intermediate revisions by 25 users not shown) | |||
Line 21: | Line 21: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">print(sum((1..1000).map(x -> 1.0/x^2)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 29: | Line 29: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* Sum of a series 30/03/2017 |
||
SUMSER CSECT |
SUMSER CSECT |
||
USING SUMSER,12 base register |
USING SUMSER,12 base register |
||
Line 52: | Line 52: | ||
COPY FORMATF formatf code |
COPY FORMATF formatf code |
||
PG DC CL80' ' buffer |
PG DC CL80' ' buffer |
||
END SUMSER</ |
END SUMSER</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 59: | Line 59: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun sum-x^-2 (max-x) |
||
(if (zp max-x) |
(if (zp max-x) |
||
0 |
0 |
||
(+ (/ (* max-x max-x)) |
(+ (/ (* max-x max-x)) |
||
(sum-x^-2 (1- max-x)))))</ |
(sum-x^-2 (1- max-x)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
|||
{{libheader|Action! Tool Kit}} |
|||
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit |
|||
PROC Calc(CARD n REAL POINTER res) |
|||
CARD i,st |
|||
BYTE perc |
|||
REAL one,a,b |
|||
IntToReal(0,res) |
|||
IF n=0 THEN RETURN FI |
|||
IntToReal(1,one) |
|||
st=n/100 |
|||
FOR i=1 TO n |
|||
DO |
|||
IF i MOD st=0 THEN |
|||
PrintB(perc) Put('%) PutE() Put(28) |
|||
perc==+1 |
|||
FI |
|||
IntToReal(i,a) |
|||
RealMult(a,a,b) |
|||
RealDiv(one,b,a) |
|||
RealAdd(res,a,b) |
|||
RealAssign(b,res) |
|||
OD |
|||
RETURN |
|||
PROC Main() |
|||
REAL POINTER res |
|||
CARD n=[1000] |
|||
Put(125) PutE() ;clear screen |
|||
Calc(n,res) |
|||
PrintF("s(%U)=",n) |
|||
PrintRE(res) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_a_series.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
s(1000)=1.64392967 |
|||
</pre> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">function partialSum(n:uint):Number |
||
{ |
{ |
||
var sum:Number = 0; |
var sum:Number = 0; |
||
Line 73: | Line 117: | ||
return sum; |
return sum; |
||
} |
} |
||
trace(partialSum(1000));</ |
trace(partialSum(1000));</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io; |
||
procedure Sum_Series is |
procedure Sum_Series is |
||
Line 95: | Line 139: | ||
Put(Item => Sum, Aft => 10, Exp => 0); |
Put(Item => Sum, Aft => 10, Exp => 0); |
||
New_Line; |
New_Line; |
||
end Sum_Series;</ |
end Sum_Series;</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">real |
||
Invsqr(real n) |
Invsqr(real n) |
||
{ |
{ |
||
Line 122: | Line 166: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
<syntaxhighlight lang="algol68">MODE RANGE = STRUCT(INT lwb, upb); |
|||
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
|||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
|||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
|||
<lang algol68>MODE RANGE = STRUCT(INT lwb, upb); |
|||
PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:( |
PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:( |
||
Line 141: | Line 180: | ||
test:( |
test:( |
||
RANGE range = (1, |
RANGE range = (1,1000); |
||
PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2; |
PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2; |
||
print(("Sum of f(x) from", lwb OF range, " to ",upb OF range," is ", SHORTEN sum(f,range),".", new line)) |
print(("Sum of f(x) from ", whole(lwb OF range, 0), " to ",whole(upb OF range, 0)," is ", fixed(SHORTEN sum(f,range),-8,5),".", new line)) |
||
)</ |
)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Sum of f(x) from |
Sum of f(x) from 1 to 1000 is 1.64393. |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
Uses [[Jensen's Device]] (first introduced in Algol 60) which uses call by name to allow a summation index and the expression to sum to be specified as parameters to a summation procedure. |
Uses [[Jensen's Device]] (first introduced in Algol 60) which uses call by name to allow a summation index and the expression to sum to be specified as parameters to a summation procedure. |
||
< |
<syntaxhighlight lang="algolw">begin % compute the sum of 1/k^2 for k = 1..1000 % |
||
integer k; |
integer k; |
||
% computes the sum of a series from lo to hi using Jensen's Device % |
% computes the sum of a series from lo to hi using Jensen's Device % |
||
Line 167: | Line 206: | ||
end; |
end; |
||
write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) ) |
write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) ) |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 174: | Line 213: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl"> +/÷2*⍨⍳1000 |
||
1.64393</ |
1.64393</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
{{Trans|JavaScript}} |
{{Trans|JavaScript}} |
||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang="applescript">----------------------- SUM OF SERIES ---------------------- |
||
-- seriesSum :: Num a => (a -> a) -> [a] -> a |
-- seriesSum :: Num a => (a -> a) -> [a] -> a |
||
Line 248: | Line 287: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<lang |
<syntaxhighlight lang="applescript">1.643934566682</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">series: map 1..1000 => [1.0/&^2] |
||
print [sum series]</ |
print [sum series]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.643934566681561</pre> |
<pre>1.643934566681561</pre> |
||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="Asymptote">real sum; |
|||
for(int i = 1; i < 1000; ++i) sum = sum + 1 / (i * i); |
|||
write(sum, suffix=none);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.64393356668156</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
AutoHotkey allows the precision of floating point numbers generated by math operations to be adjusted via the SetFormat command. The default is 6 decimal places. |
AutoHotkey allows the precision of floating point numbers generated by math operations to be adjusted via the SetFormat command. The default is 6 decimal places. |
||
< |
<syntaxhighlight lang="autohotkey">SetFormat, FloatFast, 0.15 |
||
While A_Index <= 1000 |
While A_Index <= 1000 |
||
sum += 1/A_Index**2 |
sum += 1/A_Index**2 |
||
MsgBox,% sum ;1.643934566681554</ |
MsgBox,% sum ;1.643934566681554</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}' |
||
1.64393</ |
1.64393</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
< |
<syntaxhighlight lang="qbasic">function s(x%) |
||
s = 1 / x ^ 2 |
s = 1 / x ^ 2 |
||
end function |
end function |
||
Line 284: | Line 330: | ||
sum = ret |
sum = ret |
||
end function |
end function |
||
print sum(1, 1000)</ |
print sum(1, 1000)</syntaxhighlight> |
||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{works with|True BASIC}} |
{{works with|True BASIC}} |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
function sumSeries(n) |
function sumSeries(n) |
||
if n = 0 then sumSeries = 0 |
if n = 0 then sumSeries = 0 |
||
Line 301: | Line 347: | ||
print "zeta(2) = "; pi * pi / 6 |
print "zeta(2) = "; pi * pi / 6 |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> FOR i% = 1 TO 1000 |
||
sum += 1/i%^2 |
sum += 1/i%^2 |
||
NEXT |
NEXT |
||
PRINT sum</ |
PRINT sum</syntaxhighlight> |
||
==={{header|Gambas}}=== |
|||
<syntaxhighlight lang="vbnet">Public Sub Main() |
|||
Print "s(1000) = "; sumSeries(1000) |
|||
Print "zeta(2) = "; Pi * Pi / 6 |
|||
End |
|||
Function sumSeries(n As Integer) As Float |
|||
If n = 0 Then Return 0 |
|||
Dim sum As Float = 0 |
|||
For k As Integer = 1 To n |
|||
sum += 1.0 / (k * k) |
|||
Next |
|||
Return sum |
|||
End Function</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
|||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
<syntaxhighlight lang="qbasic">FUNCTION sumSeries# (n) |
|||
IF n = 0 THEN sunSeries = 0 |
|||
FOR k = 1 TO n |
|||
sum# = sum# + 1! / (k * k) |
|||
NEXT |
|||
sumSeries# = sum# |
|||
END FUNCTION |
|||
pi# = 4 * ATN(1) |
|||
PRINT "s(1000) = "; sumSeries#(1000) |
|||
PRINT "zeta(2) = "; pi# * pi# / 6 |
|||
END</syntaxhighlight> |
|||
==={{header|True BASIC}}=== |
|||
{{works with|BASIC256}} |
|||
<syntaxhighlight lang="qbasic"> |
|||
FUNCTION sumSeries(n) |
|||
IF n = 0 then |
|||
LET sumSeries = 0 |
|||
END IF |
|||
LET sum = 0 |
|||
FOR k = 1 to n |
|||
LET sum = sum + 1 / k ^ 2 |
|||
NEXT k |
|||
LET sumSeries = sum |
|||
END FUNCTION |
|||
PRINT "s(1000) = "; sumSeries(1000) |
|||
PRINT "zeta(2) = "; pi * pi / 6 |
|||
END |
|||
</syntaxhighlight> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="qbasic">PROGRAM "SumOfASeries" |
|||
VERSION "0.0000" |
|||
DECLARE FUNCTION Entry () |
|||
DECLARE FUNCTION sumSeries#(n) |
|||
FUNCTION Entry () |
|||
pi# = 3.1415926535896 |
|||
PRINT "s(1000) = "; sumSeries#(1000) |
|||
PRINT "zeta(2) = "; pi# * pi# / 6 |
|||
END FUNCTION |
|||
FUNCTION sumSeries#(n) |
|||
IF n = 0 THEN RETURN 0 |
|||
sum# = 0 |
|||
FOR k = 1 TO n |
|||
sum# = sum# + 1.0/(k * k) |
|||
NEXT |
|||
RETURN sum# |
|||
END FUNCTION |
|||
END PROGRAM</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic"> |
|||
sub sumSeries(n) |
|||
if n = 0 then return 0 : fi |
|||
sum = 0 |
|||
for k = 1 to n |
|||
sum = sum + 1 / k ^ 2 |
|||
next k |
|||
return sum |
|||
end sub |
|||
print "s(1000) = ", sumSeries(1000) |
|||
print "zeta(2) = ", pi * pi / 6 |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
< |
<syntaxhighlight lang="bc">define f(x) { |
||
return(1 / (x * x)) |
return(1 / (x * x)) |
||
} |
} |
||
Line 325: | Line 468: | ||
scale = 20 |
scale = 20 |
||
s(1000)</ |
s(1000)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 331: | Line 474: | ||
=={{header|Beads}}== |
=={{header|Beads}}== |
||
< |
<syntaxhighlight lang="beads">beads 1 program 'Sum of a series' |
||
calc main_init |
calc main_init |
||
var k = 0 |
var k = 0 |
||
loop reps:1000 count:n |
loop reps:1000 count:n |
||
k = k + 1/n^2 |
k = k + 1/n^2 |
||
log to_str(k)</ |
log to_str(k)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.6439345666815615</pre> |
<pre>1.6439345666815615</pre> |
||
Line 342: | Line 485: | ||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
Emulates fixed point arithmetic with a 32 bit integer so the result is not very accurate. |
Emulates fixed point arithmetic with a 32 bit integer so the result is not very accurate. |
||
< |
<syntaxhighlight lang="befunge">05558***>::"~"%00p"~"/10p"( }}2"*v |
||
v*8555$_^#!:-1+*"~"g01g00+/*:\***< |
v*8555$_^#!:-1+*"~"g01g00+/*:\***< |
||
<@$_,#!>#:<+*<v+*86%+55:p00<6\0/** |
<@$_,#!>#:<+*<v+*86%+55:p00<6\0/** |
||
"."\55+%68^>\55+/00g1-:#^_$</ |
"."\55+%68^>\55+/00g1-:#^_$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.643934</pre> |
<pre>1.643934</pre> |
||
=={{header|BQN}}== |
|||
<code>√⁼</code> here reads as the inverse of the square root, which can be changed to <code>2⋆˜</code> or <code>ט</code>. It has been used here since it is the most intuitive. |
|||
<syntaxhighlight lang="bqn"> +´÷√⁼1+↕1000 |
|||
1.6439345666815597</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( 0:?i |
||
& 0:?S |
& 0:?S |
||
& whl'(1+!i:~>1000:?i&!i^-2+!S:?S) |
& whl'(1+!i:~>1000:?i&!i^-2+!S:?S) |
||
& out$!S |
& out$!S |
||
& out$(flt$(!S,10)) |
& out$(flt$(!S,10)) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>8354593848314...../5082072010432..... (1732 digits and a slash) |
<pre>8354593848314...../5082072010432..... (1732 digits and a slash) |
||
Line 361: | Line 511: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
double Invsqr(double n) |
double Invsqr(double n) |
||
Line 382: | Line 532: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">class Program |
||
{ |
{ |
||
static void Main(string[] args) |
static void Main(string[] args) |
||
Line 403: | Line 553: | ||
Console.ReadLine(); |
Console.ReadLine(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
An alternative approach using Enumerable.Range() to generate the numbers. |
An alternative approach using Enumerable.Range() to generate the numbers. |
||
< |
<syntaxhighlight lang="csharp">class Program |
||
{ |
{ |
||
static void Main(string[] args) |
static void Main(string[] args) |
||
Line 416: | Line 566: | ||
Console.ReadLine(); |
Console.ReadLine(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
double f(double x); |
double f(double x); |
||
Line 441: | Line 591: | ||
{ |
{ |
||
return ( 1.0 / ( x * x ) ); |
return ( 1.0 / ( x * x ) ); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|CLIPS}}== |
=={{header|CLIPS}}== |
||
< |
<syntaxhighlight lang="clips">(deffunction S (?x) (/ 1 (* ?x ?x))) |
||
(deffunction partial-sum-S |
(deffunction partial-sum-S |
||
(?start ?stop) |
(?start ?stop) |
||
Line 452: | Line 602: | ||
) |
) |
||
(return ?sum) |
(return ?sum) |
||
)</ |
)</syntaxhighlight> |
||
Usage: |
Usage: |
||
Line 459: | Line 609: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(reduce + (map #(/ 1.0 % %) (range 1 1001)))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">series_sum = proc (from, to: int, |
|||
fn: proctype (real) returns (real)) |
|||
returns (real) |
|||
sum: real := 0.0 |
|||
for i: int in int$from_to(from, to) do |
|||
sum := sum + fn(real$i2r(i)) |
|||
end |
|||
return(sum) |
|||
end series_sum |
|||
one_over_k_squared = proc (k: real) returns (real) |
|||
return(1.0 / (k * k)) |
|||
end one_over_k_squared |
|||
start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
result: real := series_sum(1, 1000, one_over_k_squared) |
|||
stream$putl(po, f_form(result, 1, 6)) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.643935</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. sum-of-series. |
PROGRAM-ID. sum-of-series. |
||
Line 480: | Line 653: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 487: | Line 660: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
<syntaxhighlight lang="coffeescript"> |
|||
<lang CoffeeScript> |
|||
console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x))) |
console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(loop for x from 1 to 1000 summing (expt x -2))</syntaxhighlight> |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="ruby">puts (1..1000).sum{ |x| 1.0 / x ** 2 } |
||
puts (1..5000).sum{ |x| 1.0 / x ** 2 } |
puts (1..5000).sum{ |x| 1.0 / x ** 2 } |
||
puts (1..9999).sum{ |x| 1.0 / x ** 2 } |
puts (1..9999).sum{ |x| 1.0 / x ** 2 } |
||
puts Math::PI ** 2 / 6</ |
puts Math::PI ** 2 / 6</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 510: | Line 683: | ||
=={{header|D}}== |
=={{header|D}}== |
||
===More Procedural Style=== |
===More Procedural Style=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.traits; |
||
ReturnType!TF series(TF)(TF func, int end, int start=1) |
ReturnType!TF series(TF)(TF func, int end, int start=1) |
||
Line 522: | Line 695: | ||
void main() { |
void main() { |
||
writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000)); |
writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Sum: 1.64393</pre> |
<pre>Sum: 1.64393</pre> |
||
Line 528: | Line 701: | ||
===More functional Style=== |
===More functional Style=== |
||
Same output. |
Same output. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
enum series(alias F) = (in int end, in int start=1) |
enum series(alias F) = (in int end, in int start=1) |
||
Line 535: | Line 708: | ||
void main() { |
void main() { |
||
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000)); |
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|dc}}== |
|||
<syntaxhighlight lang="dc">20 k 0 [ln 1 + d sn _2 ^ + 1000 ln <l] d sl x p</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.64393456668155979824</pre> |
|||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
{{trans|Scala}} |
{{trans|Scala}} |
||
< |
<syntaxhighlight lang="dart">main() { |
||
var list = new List<int>.generate(1000, (i) => i + 1); |
var list = new List<int>.generate(1000, (i) => i + 1); |
||
Line 548: | Line 726: | ||
}); |
}); |
||
print(sum); |
print(sum); |
||
}</ |
}</syntaxhighlight> |
||
{{trans|F#}} |
{{trans|F#}} |
||
< |
<syntaxhighlight lang="dart">f(double x) { |
||
if (x == 0) |
if (x == 0) |
||
return x; |
return x; |
||
Line 560: | Line 738: | ||
main() { |
main() { |
||
print(f(1000)); |
print(f(1000)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
unit Form_SumOfASeries_Unit; |
unit Form_SumOfASeries_Unit; |
||
Line 611: | Line 789: | ||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>1.64393456668156</pre> |
<pre>1.64393456668156</pre> |
||
Line 617: | Line 795: | ||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi"> |
||
var s : Float; |
var s : Float; |
||
for var i := 1 to 1000 do |
for var i := 1 to 1000 do |
||
Line 623: | Line 801: | ||
PrintLn(s); |
PrintLn(s); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Line 629: | Line 807: | ||
{{trans|Swift}} |
{{trans|Swift}} |
||
< |
<syntaxhighlight lang="dyalect">func Integer.SumSeries() { |
||
var ret = 0 |
var ret = 0 |
||
Line 640: | Line 818: | ||
var x = 1000 |
var x = 1000 |
||
print(x. |
print(x.SumSeries())</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 648: | Line 826: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">pragma.enable("accumulator") |
||
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }</ |
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
numfmt 8 0 |
|||
for i = 1 to 1000 |
|||
s += 1 / (i * i) |
|||
. |
|||
print s |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(lib 'math) ;; for (sigma f(n) nfrom nto) function |
(lib 'math) ;; for (sigma f(n) nfrom nto) function |
||
(Σ (λ(n) (// (* n n))) 1 1000) |
(Σ (λ(n) (// (* n n))) 1 1000) |
||
Line 661: | Line 848: | ||
(// (* PI PI) 6) |
(// (* PI PI) 6) |
||
→ 1.6449340668482264 |
→ 1.6449340668482264 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
Line 667: | Line 854: | ||
In floating-point arithmetic, summing the smallest terms first is more accurate than summing the largest terms first, as can be seen e.g. in the Pascal solution. EDSAC used fixed-point arithmetic, so the order of summation makes no difference. |
In floating-point arithmetic, summing the smallest terms first is more accurate than summing the largest terms first, as can be seen e.g. in the Pascal solution. EDSAC used fixed-point arithmetic, so the order of summation makes no difference. |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Sum of a series, Rosetta Code website. |
[Sum of a series, Rosetta Code website. |
||
EDSAC program, Initial Orders 2.] |
EDSAC program, Initial Orders 2.] |
||
Line 730: | Line 917: | ||
[89] O5@ ZF [flush teleprinter buffer; stop] |
[89] O5@ ZF [flush teleprinter buffer; stop] |
||
E15Z PF [define entry point; enter with acc = 0] |
E15Z PF [define entry point; enter with acc = 0] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 738: | Line 925: | ||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
note |
note |
||
description: "Compute the n-th term of a series" |
description: "Compute the n-th term of a series" |
||
Line 790: | Line 977: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions; |
import extensions; |
||
public program() |
public program() |
||
{ |
{ |
||
var sum := new Range(1, 1000).selectBy:(x => 1.0r / (x * x)).summarize(new Real()); |
var sum := new Range(1, 1000).selectBy::(x => 1.0r / (x * x)).summarize(new Real()); |
||
console.printLine |
console.printLine(sum) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 809: | Line 996: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end) |
||
1.6439345666815615</ |
1.6439345666815615</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
|||
<lang Emacs Lisp> |
|||
(defun serie (n) |
|||
(if (< 0 n) |
|||
(apply '+ (mapcar (lambda (k) (/ 1.0 (* k k) )) (number-sequence 1 n) )) |
|||
(error "input error") )) |
|||
=={{header|Elm}}== |
|||
(insert (format "%.10f" (serie 1000) )) |
|||
< |
<syntaxhighlight lang="elm"> |
||
module Main exposing (main) |
|||
<b>Output:</b> |
|||
import Html exposing (h1, div, p, text) |
|||
import Html.Attributes exposing (style) |
|||
aList : List Int |
|||
aList = List.range 1 1000 |
|||
-- version a with a list |
|||
k2xSum : Float |
|||
k2xSum = List.sum |
|||
<| List.map (\x -> 1.0 / x / x ) |
|||
<| List.map (\n -> toFloat n) aList |
|||
-- version b with a list |
|||
fx : Int -> Float |
|||
fx = |
|||
(\n -> toFloat n |> \m -> 1.0 / m / m) |
|||
f2kSum : Float |
|||
f2kSum = List.sum |
|||
<| List.map fx aList |
|||
-- version with recursion, without a list |
|||
untilMax : Int -> Int -> Float -> Float |
|||
untilMax k kmax accum = |
|||
if k > kmax |
|||
then accum |
|||
else |
|||
let |
|||
x = toFloat k |
|||
dx = 1.0 / x / x |
|||
in untilMax (k + 1) kmax (accum + dx) |
|||
recSum : Float |
|||
recSum = untilMax 1 1000 0.0 |
|||
main = div [style "margin" "5%", style "color" "blue"] [ |
|||
h1 [] [text "Sum of series Σ 1/k²"] |
|||
, text (" Version a with a list: Sum = " ++ String.fromFloat k2xSum) |
|||
, p [] [text (" Version b with a list: Sum = " ++ String.fromFloat f2kSum)] |
|||
, p [] [text (" Recursion version c: Sum = " ++ String.fromFloat recSum)] |
|||
] |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
<pre> |
||
Sum of series Σ 1/k² |
|||
1.6439345667 |
|||
Version a with a list: Sum = 1.6439345666815615 |
|||
Version b with a list: Sum = 1.6439345666815615 |
|||
Recursion version c: Sum = 1.6439345666815615 |
|||
</pre> |
</pre> |
||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp">(defun series (n) |
|||
(when (<= n 0) |
|||
(user-error "n must be positive")) |
|||
(apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n)))) |
|||
(format "%.10f" (series 1000)) ;=> "1.6439345667"</syntaxhighlight> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]).</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
{{works with|Euphoria|4.0.0}} |
{{works with|Euphoria|4.0.0}} |
||
This is based on the [[BASIC]] example. |
This is based on the [[BASIC]] example. |
||
<syntaxhighlight lang="euphoria"> |
|||
<lang Euphoria> |
|||
function s( atom x ) |
function s( atom x ) |
||
return 1 / power( x, 2 ) |
return 1 / power( x, 2 ) |
||
Line 846: | Line 1,087: | ||
end function |
end function |
||
printf( 1, "%.15f\n", sum( 1, 1000 ) )</ |
printf( 1, "%.15f\n", sum( 1, 1000 ) )</syntaxhighlight> |
||
=={{header|Excel}}== |
=={{header|Excel}}== |
||
Line 858: | Line 1,099: | ||
{{Works with|Office 365 betas 2021}} |
{{Works with|Office 365 betas 2021}} |
||
< |
<syntaxhighlight lang="lisp">sumOfSeries |
||
=LAMBDA(f, |
=LAMBDA(f, |
||
LAMBDA(n, |
LAMBDA(n, |
||
Line 871: | Line 1,112: | ||
=LAMBDA(n, |
=LAMBDA(n, |
||
1 / (n ^ 2) |
1 / (n ^ 2) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 905: | Line 1,146: | ||
=={{header|Ezhil}}== |
=={{header|Ezhil}}== |
||
<syntaxhighlight lang="ezhil"> |
|||
<lang Ezhil> |
|||
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது |
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது |
||
Line 931: | Line 1,172: | ||
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ) |
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
The following function will do the task specified. |
The following function will do the task specified. |
||
< |
<syntaxhighlight lang="fsharp">let rec f (x : float) = |
||
match x with |
match x with |
||
| 0. -> x |
| 0. -> x |
||
| x -> (1. / (x * x)) + f (x - 1.)</ |
| x -> (1. / (x * x)) + f (x - 1.)</syntaxhighlight> |
||
In the interactive F# console, using the above gives: |
In the interactive F# console, using the above gives: |
||
< |
<syntaxhighlight lang="fsharp">> f 1000. ;; |
||
val it : float = 1.643934567</ |
val it : float = 1.643934567</syntaxhighlight> |
||
However, this recursive function will run out of stack space eventually (try 100000). A [[:Category:Recursion|tail-recursive]] implementation will not consume stack space and can therefore handle much larger ranges. Here is such a version: |
However, this recursive function will run out of stack space eventually (try 100000). A [[:Category:Recursion|tail-recursive]] implementation will not consume stack space and can therefore handle much larger ranges. Here is such a version: |
||
< |
<syntaxhighlight lang="fsharp">#light |
||
let sum_series (max : float) = |
let sum_series (max : float) = |
||
let rec f (a:float, x : float) = |
let rec f (a:float, x : float) = |
||
Line 955: | Line 1,196: | ||
let (b, max) = System.Double.TryParse(args.[0]) |
let (b, max) = System.Double.TryParse(args.[0]) |
||
printfn "%A" (sum_series max) |
printfn "%A" (sum_series max) |
||
0</ |
0</syntaxhighlight> |
||
This block can be compiled using ''fsc --target exe filename.fs'' or used interactively without the main function. |
This block can be compiled using ''fsc --target exe filename.fs'' or used interactively without the main function. |
||
For a much more elegant and FP style of solving this problem, use: |
For a much more elegant and FP style of solving this problem, use: |
||
< |
<syntaxhighlight lang="fsharp"> |
||
Seq.sum [for x in [1..1000] do 1./(x * x |> float)] |
Seq.sum [for x in [1..1000] do 1./(x * x |> float)] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">1000 [1,b] [ >float sq recip ] map-sum</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 970: | Line 1,211: | ||
Within 'fansh': |
Within 'fansh': |
||
< |
<syntaxhighlight lang="fantom"> |
||
fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) } |
fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) } |
||
1.6439345666815615 |
1.6439345666815615 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat">Sigma<k=1,1000>[1/k^2]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 997: | Line 1,238: | ||
=={{header|Fish}}== |
=={{header|Fish}}== |
||
< |
<syntaxhighlight lang="fish">0&aaa**>::*1$,&v |
||
;n&^?:-1&+ <</ |
;n&^?:-1&+ <</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: sum ( fn start count -- fsum ) |
||
0e |
0e |
||
bounds do |
bounds do |
||
Line 1,009: | Line 1,250: | ||
:noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt ) |
:noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt ) |
||
1 1000 sum f. \ 1.64393456668156 |
1 1000 sum f. \ 1.64393456668156 |
||
pi pi f* 6e f/ f. \ 1.64493406684823</ |
pi pi f* 6e f/ f. \ 1.64493406684823</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 and later, use SUM intrinsic: |
In ISO Fortran 90 and later, use SUM intrinsic: |
||
< |
<syntaxhighlight lang="fortran">real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /) |
||
real :: result |
real :: result |
||
result = sum(a);</ |
result = sum(a);</syntaxhighlight> |
||
Or in Fortran 77: |
Or in Fortran 77: |
||
< |
<syntaxhighlight lang="fortran"> s=0 |
||
do i=1,1000 |
do i=1,1000 |
||
s=s+1./i**2 |
s=s+1./i**2 |
||
end do |
end do |
||
write (*,*) s |
write (*,*) s |
||
end</ |
end</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Const pi As Double = 3.141592653589793 |
Const pi As Double = 3.141592653589793 |
||
Line 1,043: | Line 1,284: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,053: | Line 1,294: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
Frink can calculate the series with exact rational numbers or floating-point values. |
Frink can calculate the series with exact rational numbers or floating-point values. |
||
< |
<syntaxhighlight lang="frink"> |
||
sum[map[{|k| 1/k^2}, 1 to 1000]] |
sum[map[{|k| 1/k^2}, 1 to 1000]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,064: | Line 1,305: | ||
=={{header|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_of_a_series}} |
|||
'''Solution''' |
|||
In the following function, the first parameter is the series is provided as a lambda expression. The second parameter is the number of terms to calculate |
|||
[[File:Fōrmulæ - Sum of a series 01.png]] |
|||
'''Test case''' |
|||
The exact value (of the sum) is: |
|||
[[File:Fōrmulæ - Sum of a series 02.png]] |
|||
(click to enlarge) |
|||
[[File:Fōrmulæ - Sum of a series 03.png|750px||link=https://static.wikiforge.net/rosettacodewikitide/0/0f/F%C5%8Drmul%C3%A6_-_Sum_of_a_series_03.png]] |
|||
The approximate value is: |
|||
[[File:Fōrmulæ - Sum of a series 04.png]] |
|||
[[File:Fōrmulæ - Sum of a series 05.png]] |
|||
While the (approximate) value of π<sup>2</sup>/6 is: |
|||
[[File:Fōrmulæ - Sum of a series 06.png]] |
|||
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for transportation effects more than visualization and edition. |
|||
[[File:Fōrmulæ - Sum of a series 07.png]] |
|||
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code. |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># We will compute the sum exactly |
||
# Computing an approximation of a rationnal (giving a string) |
# Computing an approximation of a rationnal (giving a string) |
||
Line 1,102: | Line 1,367: | ||
Approx(a, 10); |
Approx(a, 10); |
||
"1.6439345666" |
"1.6439345666" |
||
# and pi^2/6 is 1.6449340668, truncated to ten digits</ |
# and pi^2/6 is 1.6449340668, truncated to ten digits</syntaxhighlight> |
||
=={{header|Genie}}== |
=={{header|Genie}}== |
||
< |
<syntaxhighlight lang="genie">[indent=4] |
||
/* |
/* |
||
Sum of series, in Genie |
Sum of series, in Genie |
||
Line 1,126: | Line 1,391: | ||
Intl.setlocale() |
Intl.setlocale() |
||
print "ζ(2) approximation: %16.15f", sum_series(1, 1000, oneOverSquare) |
print "ζ(2) approximation: %16.15f", sum_series(1, 1000, oneOverSquare) |
||
print "π² / 6 : %16.15f", Math.PI * Math.PI / 6.0</ |
print "π² / 6 : %16.15f", Math.PI * Math.PI / 6.0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,135: | Line 1,400: | ||
=={{header|GEORGE}}== |
=={{header|GEORGE}}== |
||
<syntaxhighlight lang="george"> |
|||
<lang GEORGE> |
|||
0 (s) |
0 (s) |
||
1, 1000 rep (i) |
1, 1000 rep (i) |
||
Line 1,141: | Line 1,406: | ||
] |
] |
||
P |
P |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output:- |
Output:- |
||
<pre> |
<pre> |
||
Line 1,148: | Line 1,413: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ("fmt"; "math") |
import ("fmt"; "math") |
||
Line 1,159: | Line 1,424: | ||
} |
} |
||
fmt.Println("computed:", sum) |
fmt.Println("computed:", sum) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>known: 1.6449340668482264 |
<pre>known: 1.6449340668482264 |
||
Line 1,166: | Line 1,431: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Start with smallest terms first to minimize rounding error: |
Start with smallest terms first to minimize rounding error: |
||
< |
<syntaxhighlight lang="groovy">println ((1000..1).collect { x -> 1/(x*x) }.sum())</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,173: | Line 1,438: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
With a list comprehension: |
With a list comprehension: |
||
< |
<syntaxhighlight lang="haskell">sum [1 / x ^ 2 | x <- [1..1000]]</syntaxhighlight> |
||
With higher-order functions: |
With higher-order functions: |
||
< |
<syntaxhighlight lang="haskell">sum $ map (\x -> 1 / x ^ 2) [1..1000]</syntaxhighlight> |
||
In [http://haskell.org/haskellwiki/Pointfree point-free] style: |
In [http://haskell.org/haskellwiki/Pointfree point-free] style: |
||
< |
<syntaxhighlight lang="haskell">(sum . map (1/) . map (^2)) [1..1000]</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="haskell">(sum . map ((1 /) . (^ 2))) [1 .. 1000]</syntaxhighlight> |
||
or, as a single fold: |
or, as a single fold: |
||
< |
<syntaxhighlight lang="haskell">seriesSum f = foldr ((+) . f) 0 |
||
inverseSquare = (1 /) . (^ 2) |
inverseSquare = (1 /) . (^ 2) |
||
main :: IO () |
main :: IO () |
||
main = print $ seriesSum inverseSquare [1 .. 1000]</ |
main = print $ seriesSum inverseSquare [1 .. 1000]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1.6439345666815615</pre> |
<pre>1.6439345666815615</pre> |
||
Line 1,194: | Line 1,459: | ||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang="haxe">using StringTools; |
||
class Main { |
class Main { |
||
Line 1,204: | Line 1,469: | ||
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6); |
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,213: | Line 1,478: | ||
===Functional=== |
===Functional=== |
||
< |
<syntaxhighlight lang="haxe">using Lambda; |
||
using StringTools; |
using StringTools; |
||
Line 1,222: | Line 1,487: | ||
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6); |
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,228: | Line 1,493: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: a(1000) |
||
a = 1 / $^2 |
a = 1 / $^2 |
||
WRITE(ClipBoard, Format='F17.15') SUM(a) </ |
WRITE(ClipBoard, Format='F17.15') SUM(a) </syntaxhighlight> |
||
<lang |
<syntaxhighlight lang="hicest">1.643934566681561</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
local i, sum |
local i, sum |
||
sum := 0 & i := 0 |
sum := 0 & i := 0 |
||
every sum +:= 1.0/((| i +:= 1 ) ^ 2) \1000 |
every sum +:= 1.0/((| i +:= 1 ) ^ 2) \1000 |
||
write(sum) |
write(sum) |
||
end</ |
end</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
every (sum := 0) +:= 1.0/((1 to 1000)^2) |
every (sum := 0) +:= 1.0/((1 to 1000)^2) |
||
write(sum) |
write(sum) |
||
end</ |
end</syntaxhighlight> |
||
Note: The terse version requires some explanation. Icon expressions all return values or references if they succeed. As a result, it is possible to have expressions like these below: |
Note: The terse version requires some explanation. Icon expressions all return values or references if they succeed. As a result, it is possible to have expressions like these below: |
||
< |
<syntaxhighlight lang="icon"> |
||
x := y := 0 # := is right associative so, y is assigned 0, then x |
x := y := 0 # := is right associative so, y is assigned 0, then x |
||
1 < x < 99 # comparison operators are left associative so, 1 < x returns x (if it is greater than 1), then x < 99 returns 99 if the comparison succeeds |
1 < x < 99 # comparison operators are left associative so, 1 < x returns x (if it is greater than 1), then x < 99 returns 99 if the comparison succeeds |
||
(sum := 0) # returns a reference to sum which can in turn be used with augmented assignment +:= |
(sum := 0) # returns a reference to sum which can in turn be used with augmented assignment +:= |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
< |
<syntaxhighlight lang="idl">print,total( 1/(1+findgen(1000))^2)</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
Line 1,269: | Line 1,534: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> NB. sum of reciprocals of squares of first thousand positive integers |
||
+/ % *: >: i. 1000 |
+/ % *: >: i. 1000 |
||
1.64393 |
1.64393 |
||
Line 1,277: | Line 1,542: | ||
1r6p2 NB. As a constant (J has a rich constant notation) |
1r6p2 NB. As a constant (J has a rich constant notation) |
||
1.64493</ |
1.64493</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class Sum{ |
||
public static double f(double x){ |
public static double f(double x){ |
||
return 1/(x*x); |
return 1/(x*x); |
||
Line 1,294: | Line 1,559: | ||
System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum); |
System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">function sum(a,b,fn) { |
||
var s = 0; |
var s = 0; |
||
for ( ; a <= b; a++) s += fn(a); |
for ( ; a <= b; a++) s += fn(a); |
||
Line 1,304: | Line 1,569: | ||
} |
} |
||
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156</ |
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156</syntaxhighlight> |
||
or, in a functional idiom: |
or, in a functional idiom: |
||
< |
<syntaxhighlight lang="javascript">(function () { |
||
function sum(fn, lstRange) { |
function sum(fn, lstRange) { |
||
Line 1,332: | Line 1,597: | ||
); |
); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<lang |
<syntaxhighlight lang="javascript">1.6439345666815615</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,364: | Line 1,629: | ||
return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000)); |
return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000)); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<lang |
<syntaxhighlight lang="javascript">1.6439345666815615</syntaxhighlight> |
||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">1000 [0] [swap -2 pow +] primrec.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.64393</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,372: | Line 1,642: | ||
Directly: |
Directly: |
||
< |
<syntaxhighlight lang="jq">def s(n): reduce range(1; n+1) as $k (0; . + 1/($k * $k) ); |
||
s(1000) |
s(1000) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
1.6439345666815615 |
1.6439345666815615 |
||
Line 1,381: | Line 1,651: | ||
Using a generic summation wrapper function allows problems specified in "sigma" notation to be solved using syntax that closely resembles that notation: |
Using a generic summation wrapper function allows problems specified in "sigma" notation to be solved using syntax that closely resembles that notation: |
||
< |
<syntaxhighlight lang="jq">def summation(s): reduce s as $k (0; . + $k); |
||
summation( range(1; 1001) | (1/(. * .) ) )</ |
summation( range(1; 1001) | (1/(. * .) ) )</syntaxhighlight> |
||
An important point is that nothing is lost in efficiency using the declarative and quite elegant approach using "summation". |
An important point is that nothing is lost in efficiency using the declarative and quite elegant approach using "summation". |
||
Line 1,390: | Line 1,660: | ||
From Javascript ES5. |
From Javascript ES5. |
||
< |
<syntaxhighlight lang="javascript">#!/usr/bin/jsish |
||
/* Sum of a series */ |
/* Sum of a series */ |
||
function sum(a:number, b:number , fn:function):number { |
function sum(a:number, b:number , fn:function):number { |
||
Line 1,404: | Line 1,674: | ||
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561 |
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561 |
||
=!EXPECTEND!= |
=!EXPECTEND!= |
||
*/</ |
*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,413: | Line 1,683: | ||
Using a higher-order function: |
Using a higher-order function: |
||
< |
<syntaxhighlight lang="julia">julia> sum(k -> 1/k^2, 1:1000) |
||
1.643934566681559 |
1.643934566681559 |
||
julia> pi^2/6 |
julia> pi^2/6 |
||
1.6449340668482264 |
1.6449340668482264 |
||
</syntaxhighlight> |
|||
</lang> |
|||
A simple loop is more optimized: |
A simple loop is more optimized: |
||
< |
<syntaxhighlight lang="julia">julia> function f(n) |
||
s = 0.0 |
s = 0.0 |
||
for k = 1:n |
for k = 1:n |
||
Line 1,431: | Line 1,701: | ||
julia> f(1000) |
julia> f(1000) |
||
1.6439345666815615</ |
1.6439345666815615</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> ssr: +/1%_sqr |
||
ssr 1+!1000 |
ssr 1+!1000 |
||
1.643935</ |
1.643935</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,446: | Line 1,716: | ||
println("Actual sum is $sum") |
println("Actual sum is $sum") |
||
println("zeta(2) is ${Math.PI * Math.PI / 6.0}") |
println("zeta(2) is ${Math.PI * Math.PI / 6.0}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,455: | Line 1,725: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
{+ {S.map {lambda {:k} {/ 1 {* :k :k}}} {S.serie 1 1000}}} |
{+ {S.map {lambda {:k} {/ 1 {* :k :k}}} {S.serie 1 1000}}} |
||
-> 1.6439345666815615 ~ 1.6449340668482264 = PI^2/6 |
-> 1.6439345666815615 ~ 1.6449340668482264 = PI^2/6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">1000 iota 1 + 1 swap / 2 ** '+ reduce .</syntaxhighlight> |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">writeln "calc.: ", fold fn{+}, map fn(.x) { 1/.x^2 }, 1..1000 |
|||
writeln "known: ", pi^2/6</syntaxhighlight> |
|||
{{out}} |
|||
<pre>calc.: 1.643934566681559803139058023822206 |
|||
exact: 1.644934066848226436472415166646025 |
|||
</pre> |
|||
If we set a higher arbitrary maximum for division, we get more digits. |
|||
<syntaxhighlight lang="langur">mode divMaxScale = 100 |
|||
writeln "calc.: ", fold fn{+}, map fn(.x) 1/.x^2, 1..1000 |
|||
writeln "known: ", pi^2/6</syntaxhighlight> |
|||
{{out}} |
|||
<pre>calc.: 1.6439345666815598031390580238222155896521034464936853167172372054281147052136371544864376381235947140 |
|||
exact: 1.6449340668482264364724151666460251892189499012067984377355582293700074704032008738336289006197587053 |
|||
</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define sum_of_a_series(n::integer,k::integer) => { |
||
local(sum = 0) |
local(sum = 0) |
||
loop(-from=#k,-to=#n) => { |
loop(-from=#k,-to=#n) => { |
||
Line 1,471: | Line 1,762: | ||
return #sum |
return #sum |
||
} |
} |
||
sum_of_a_series(1000,1)</ |
sum_of_a_series(1000,1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.643935</pre> |
<pre>1.643935</pre> |
||
Line 1,479: | Line 1,770: | ||
=== With <code>lists:foldl</code> === |
=== With <code>lists:foldl</code> === |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun sum-series (nums) |
(defun sum-series (nums) |
||
(lists:foldl |
(lists:foldl |
||
Line 1,487: | Line 1,778: | ||
(lambda (x) (/ 1 x x)) |
(lambda (x) (/ 1 x x)) |
||
nums))) |
nums))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== With <code>lists:sum</code> === |
=== With <code>lists:sum</code> === |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun sum-series (nums) |
(defun sum-series (nums) |
||
(lists:sum |
(lists:sum |
||
Line 1,497: | Line 1,788: | ||
(lambda (x) (/ 1 x x)) |
(lambda (x) (/ 1 x x)) |
||
nums))) |
nums))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Both have the same result: |
Both have the same result: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (sum-series (lists:seq 1 100000)) |
> (sum-series (lists:seq 1 100000)) |
||
1.6449240668982423 |
1.6449240668982423 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
for i =1 to 1000 |
for i =1 to 1000 |
||
sum =sum +1 /( i^2) |
sum =sum +1 /( i^2) |
||
Line 1,515: | Line 1,806: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">the floatprecision = 8 |
||
sum = 0 |
sum = 0 |
||
repeat with i = 1 to 1000 |
repeat with i = 1 to 1000 |
||
Line 1,524: | Line 1,815: | ||
end repeat |
end repeat |
||
put sum |
put sum |
||
-- 1.64393457</ |
-- 1.64393457</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">repeat with i = 1 to 1000 |
||
add 1/(i^2) to summ |
add 1/(i^2) to summ |
||
end repeat |
end repeat |
||
put summ //1.643935</ |
put summ //1.643935</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to series :fn :a :b |
||
localmake "sigma 0 |
localmake "sigma 0 |
||
for [i :a :b] [make "sigma :sigma + invoke :fn :i] |
for [i :a :b] [make "sigma :sigma + invoke :fn :i] |
||
Line 1,543: | Line 1,834: | ||
print series "zeta.2 1 1000 |
print series "zeta.2 1 1000 |
||
make "pi (radarctan 0 1) * 2 |
make "pi (radarctan 0 1) * 2 |
||
print :pi * :pi / 6</ |
print :pi * :pi / 6</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
sum = 0 |
sum = 0 |
||
for i = 1, 1000 do sum = sum + 1/i^2 end |
for i = 1, 1000 do sum = sum + 1/i^2 end |
||
print(sum) |
print(sum) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
< |
<syntaxhighlight lang="lucid">series = ssum asa n >= 1000 |
||
where |
where |
||
num = 1 fby num + 1; |
num = 1 fby num + 1; |
||
ssum = ssum + 1/(num * num) |
ssum = ssum + 1/(num * num) |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">sum(1/k^2, k=1..1000);</syntaxhighlight> |
||
{{Out|Output}} |
{{Out|Output}} |
||
<pre>-Psi(1, 1001)+(1/6)*Pi^2</pre> |
<pre>-Psi(1, 1001)+(1/6)*Pi^2</pre> |
||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
This is the straightforward solution of the task: |
This is the straightforward solution of the task: |
||
< |
<syntaxhighlight lang="mathematica">Sum[1/x^2, {x, 1, 1000}]</syntaxhighlight> |
||
However this returns a quotient of two huge integers (namely the ''exact'' sum); to get a floating point approximation, use <tt>N</tt>: |
However this returns a quotient of two huge integers (namely the ''exact'' sum); to get a floating point approximation, use <tt>N</tt>: |
||
< |
<syntaxhighlight lang="mathematica">N[Sum[1/x^2, {x, 1, 1000}]]</syntaxhighlight> |
||
or better: |
or better: |
||
< |
<syntaxhighlight lang="mathematica">NSum[1/x^2, {x, 1, 1000}]</syntaxhighlight> |
||
Which gives a higher or equal accuracy/precision. Alternatively, get Mathematica to do the whole calculation in floating point by using a floating point value in the formula: |
Which gives a higher or equal accuracy/precision. Alternatively, get Mathematica to do the whole calculation in floating point by using a floating point value in the formula: |
||
< |
<syntaxhighlight lang="mathematica">Sum[1./x^2, {x, 1, 1000}]</syntaxhighlight> |
||
Other ways include (exact, approximate,exact,approximate): |
Other ways include (exact, approximate,exact,approximate): |
||
< |
<syntaxhighlight lang="mathematica">Total[Table[1/x^2, {x, 1, 1000}]] |
||
Total[Table[1./x^2, {x, 1, 1000}]] |
Total[Table[1./x^2, {x, 1, 1000}]] |
||
Plus@@Table[1/x^2, {x, 1, 1000}] |
Plus@@Table[1/x^2, {x, 1, 1000}] |
||
Plus@@Table[1./x^2, {x, 1, 1000}]</ |
Plus@@Table[1./x^2, {x, 1, 1000}]</syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab"> sum([1:1000].^(-2)) </syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">(%i45) sum(1/x^2, x, 1, 1000); |
||
835459384831496894781878542648[806 digits]396236858699094240207812766449 |
835459384831496894781878542648[806 digits]396236858699094240207812766449 |
||
(%o45) ------------------------------------------------------------------------ |
(%o45) ------------------------------------------------------------------------ |
||
Line 1,590: | Line 1,881: | ||
(%i46) sum(1/x^2, x, 1, 1000),numer; |
(%i46) sum(1/x^2, x, 1, 1000),numer; |
||
(%o46) 1.643934566681561</ |
(%o46) 1.643934566681561</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">total = 0 |
||
for i in 1 to 1000 do |
for i in 1 to 1000 do |
||
( |
( |
||
total += 1.0 / pow i 2 |
total += 1.0 / pow i 2 |
||
) |
) |
||
print total</ |
print total</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang="min">0 1 ( |
||
((dup * 1 swap /) (id)) cleave |
((dup * 1 swap /) (id)) cleave |
||
((+) (succ)) spread |
((+) (succ)) spread |
||
) 1000 times pop print</ |
) 1000 times pop print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,612: | Line 1,903: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">zeta = function(num) |
||
return 1 / num^2 |
return 1 / num^2 |
||
end function |
end function |
||
Line 1,625: | Line 1,916: | ||
print sum(1, 1000, @zeta) |
print sum(1, 1000, @zeta) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,632: | Line 1,923: | ||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>0 П0 П1 ИП1 1 + П1 x^2 1/x ИП0 |
<syntaxhighlight lang="text">0 П0 П1 ИП1 1 + П1 x^2 1/x ИП0 |
||
+ П0 ИП1 1 0 0 0 - x>=0 03 |
+ П0 ИП1 1 0 0 0 - x>=0 03 |
||
ИП0 С/П</ |
ИП0 С/П</syntaxhighlight> |
||
=={{header|ML}}== |
=={{header|ML}}== |
||
==={{header|Standard ML}}=== |
==={{header|Standard ML}}=== |
||
<syntaxhighlight lang="standard ml"> |
|||
<lang Standard ML> |
|||
(* 1.64393456668 *) |
(* 1.64393456668 *) |
||
List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0))) |
List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|mLite}}=== |
==={{header|mLite}}=== |
||
< |
<syntaxhighlight lang="ocaml">println ` fold (+, 0) ` map (fn x = 1 / x ^ 2) ` iota (1,1000);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>1.6439345666815549</pre> |
<pre>1.6439345666815549</pre> |
||
=={{header|MMIX}}== |
=={{header|MMIX}}== |
||
< |
<syntaxhighlight lang="mmix">x IS $1 % flt calculations |
||
y IS $2 % id |
y IS $2 % id |
||
z IS $3 % z = sum series |
z IS $3 % z = sum series |
||
Line 1,755: | Line 2,046: | ||
PBNP t,1B } z = sum |
PBNP t,1B } z = sum |
||
GO $127,prtFlt print sum --> StdOut |
GO $127,prtFlt print sum --> StdOut |
||
TRAP 0,Halt,0</ |
TRAP 0,Halt,0</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>~/MIX/MMIX/Rosetta> mmix sumseries |
<pre>~/MIX/MMIX/Rosetta> mmix sumseries |
||
0.1643934566681562e1</pre> |
0.1643934566681562e1</pre> |
||
=={{header|Modula-2}}== |
|||
<syntaxhighlight lang="modula2">MODULE SeriesSum; |
|||
FROM InOut IMPORT WriteLn; |
|||
FROM RealInOut IMPORT WriteReal; |
|||
TYPE RealFunc = PROCEDURE (REAL): REAL; |
|||
PROCEDURE seriesSum(k, n: CARDINAL; f: RealFunc): REAL; |
|||
VAR total: REAL; |
|||
i: CARDINAL; |
|||
BEGIN |
|||
total := 0.0; |
|||
FOR i := k TO n DO |
|||
total := total + f(FLOAT(i)); |
|||
END; |
|||
RETURN total; |
|||
END seriesSum; |
|||
PROCEDURE oneOverKSquared(k: REAL): REAL; |
|||
BEGIN |
|||
RETURN 1.0 / (k * k); |
|||
END oneOverKSquared; |
|||
BEGIN |
|||
WriteReal(seriesSum(1, 1000, oneOverKSquared), 10); |
|||
WriteLn; |
|||
END SeriesSum.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.6439E+00</pre> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
Modula-3 uses D0 after a floating point number as a literal for <tt>LONGREAL</tt>. |
Modula-3 uses D0 after a floating point number as a literal for <tt>LONGREAL</tt>. |
||
< |
<syntaxhighlight lang="modula3">MODULE Sum EXPORTS Main; |
||
IMPORT IO, Fmt, Math; |
IMPORT IO, Fmt, Math; |
||
Line 1,780: | Line 2,101: | ||
IO.Put(Fmt.LongReal(sum)); |
IO.Put(Fmt.LongReal(sum)); |
||
IO.Put("\n"); |
IO.Put("\n"); |
||
END Sum.</ |
END Sum.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,787: | Line 2,108: | ||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
<syntaxhighlight lang="mumps"> |
|||
<lang MUMPS> |
|||
SOAS(N) |
SOAS(N) |
||
NEW SUM,I SET SUM=0 |
NEW SUM,I SET SUM=0 |
||
Line 1,793: | Line 2,114: | ||
.SET SUM=SUM+(1/((I*I))) |
.SET SUM=SUM+(1/((I*I))) |
||
QUIT SUM |
QUIT SUM |
||
</syntaxhighlight> |
|||
</lang> |
|||
This is an extrinsic function so the usage is: |
This is an extrinsic function so the usage is: |
||
<pre> |
<pre> |
||
Line 1,801: | Line 2,122: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(let (s 0) |
||
(for (i 1 1000) |
(for (i 1 1000) |
||
(inc s (div 1 (* i i)))) |
(inc s (div 1 (* i i)))) |
||
(println s))</ |
(println s))</syntaxhighlight> |
||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
< |
<syntaxhighlight lang="nial">|sum (1 / power (count 1000) 2) |
||
=1.64393</ |
=1.64393</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var s = 0.0 |
||
for n in 1..1000: s += 1 / (n * n) |
for n in 1..1000: s += 1 / (n * n) |
||
echo s</ |
echo s</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.643934566681561</pre> |
<pre>1.643934566681561</pre> |
||
=={{header|Oberon-2}}== |
|||
{{trans|Modula-2}} |
|||
<syntaxhighlight lang="oberon2">MODULE SS; |
|||
IMPORT Out; |
|||
TYPE |
|||
RealFunc = PROCEDURE(r:REAL):REAL; |
|||
PROCEDURE SeriesSum(k,n:LONGINT;f:RealFunc):REAL; |
|||
VAR |
|||
total:REAL; |
|||
i:LONGINT; |
|||
BEGIN |
|||
total := 0.0; |
|||
FOR i := k TO n DO total := total + f(i) END; |
|||
RETURN total |
|||
END SeriesSum; |
|||
PROCEDURE OneOverKSquared(k:REAL):REAL; |
|||
BEGIN RETURN 1.0 / (k * k) |
|||
END OneOverKSquared; |
|||
BEGIN |
|||
Out.Real(SeriesSum(1,1000,OneOverKSquared),10); |
|||
Out.Ln; |
|||
END SS. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.64393E+00 |
|||
</pre> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class SumSeries { |
class SumSeries { |
||
Line 1,844: | Line 2,198: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let sum a b fn = |
||
let result = ref 0. in |
let result = ref 0. in |
||
for i = a to b do |
for i = a to b do |
||
result := !result +. fn i |
result := !result +. fn i |
||
done; |
done; |
||
!result</ |
!result</syntaxhighlight> |
||
# sum 1 1000 (fun x -> 1. /. (float x ** 2.)) |
# sum 1 1000 (fun x -> 1. /. (float x ** 2.)) |
||
Line 1,858: | Line 2,212: | ||
or in a functional programming style: |
or in a functional programming style: |
||
< |
<syntaxhighlight lang="ocaml">let sum a b fn = |
||
let rec aux i r = |
let rec aux i r = |
||
if i > b then r |
if i > b then r |
||
Line 1,864: | Line 2,218: | ||
in |
in |
||
aux a 0. |
aux a 0. |
||
;;</ |
;;</syntaxhighlight> |
||
Simple recursive solution: |
Simple recursive solution: |
||
< |
<syntaxhighlight lang="ocaml">let rec sum n = if n < 1 then 0.0 else sum (n-1) +. 1.0 /. float (n*n) |
||
in sum 1000</ |
in sum 1000</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Given a vector, the sum of all its elements is simply <code>sum(vector)</code>; a range can be ''generated'' through the range notation: <code>sum(1:1000)</code> computes the sum of all numbers from 1 to 1000. To compute the requested series, we can simply write: |
Given a vector, the sum of all its elements is simply <code>sum(vector)</code>; a range can be ''generated'' through the range notation: <code>sum(1:1000)</code> computes the sum of all numbers from 1 to 1000. To compute the requested series, we can simply write: |
||
< |
<syntaxhighlight lang="octave">sum(1 ./ [1:1000] .^ 2)</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: sumSerie(s, n) 0 n seq apply(#[ s perform + ]) ;</syntaxhighlight> |
||
Usage : |
Usage : |
||
< |
<syntaxhighlight lang="oforth"> #[ sq inv ] 1000 sumSerie println</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,890: | Line 2,244: | ||
Conventionally like elsewhere: |
Conventionally like elsewhere: |
||
< |
<syntaxhighlight lang="progress (openedge abl)">def var dcResult as decimal no-undo. |
||
def var n as int no-undo. |
def var n as int no-undo. |
||
Line 1,897: | Line 2,251: | ||
end. |
end. |
||
display dcResult .</ |
display dcResult .</syntaxhighlight> |
||
or like this: |
or like this: |
||
< |
<syntaxhighlight lang="progress (openedge abl)">def var n as int no-undo. |
||
repeat n = 1 to 1000 : |
repeat n = 1 to 1000 : |
||
Line 1,907: | Line 2,261: | ||
end. |
end. |
||
display ( accum total 1 / (n * n) ) .</ |
display ( accum total 1 / (n * n) ) .</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
With higher-order functions: |
With higher-order functions: |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {SumSeries S N} |
fun {SumSeries S N} |
||
{FoldL {Map {List.number 1 N 1} S} |
{FoldL {Map {List.number 1 N 1} S} |
||
Line 1,921: | Line 2,275: | ||
end |
end |
||
in |
in |
||
{Show {SumSeries S 1000}}</ |
{Show {SumSeries S 1000}}</syntaxhighlight> |
||
Iterative: |
Iterative: |
||
< |
<syntaxhighlight lang="oz"> fun {SumSeries S N} |
||
R = {NewCell 0.} |
R = {NewCell 0.} |
||
in |
in |
||
Line 1,931: | Line 2,285: | ||
end |
end |
||
@R |
@R |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Panda}}== |
=={{header|Panda}}== |
||
< |
<syntaxhighlight lang="panda">sum{{1.0.divide(1..1000.sqr)}}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>1.6439345666815615</pre> |
<pre>1.6439345666815615</pre> |
||
Line 1,940: | Line 2,294: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Exact rational solution: |
Exact rational solution: |
||
< |
<syntaxhighlight lang="parigp">sum(n=1,1000,1/n^2)</syntaxhighlight> |
||
Real number solution (accurate to <math>3\cdot10^{-36}</math> at standard precision): |
Real number solution (accurate to <math>3\cdot10^{-36}</math> at standard precision): |
||
< |
<syntaxhighlight lang="parigp">sum(n=1,1000,1./n^2)</syntaxhighlight> |
||
Approximate solution (accurate to <math>9\cdot10^{-11}</math> at standard precision): |
Approximate solution (accurate to <math>9\cdot10^{-11}</math> at standard precision): |
||
< |
<syntaxhighlight lang="parigp">zeta(2)-intnum(x=1000.5,[1],1/x^2)</syntaxhighlight> |
||
or |
or |
||
<lang |
<syntaxhighlight lang="parigp">zeta(2)-1/1000.5</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program SumSeries; |
||
type |
type |
||
tOutput = double;//extended; |
tOutput = double;//extended; |
||
Line 1,974: | Line 2,328: | ||
writeln('The sum of 1/x^2 from 1 to 1000 is: ', Sum(1,1000,@f)); |
writeln('The sum of 1/x^2 from 1 to 1000 is: ', Sum(1,1000,@f)); |
||
writeln('Whereas pi^2/6 is: ', pi*pi/6:10:8); |
writeln('Whereas pi^2/6 is: ', pi*pi/6:10:8); |
||
end.</ |
end.</syntaxhighlight> |
||
Output |
Output |
||
<pre>different version of type and calculation |
<pre>different version of type and calculation |
||
Line 1,987: | Line 2,341: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my $sum = 0; |
||
$sum += 1 / $_ ** 2 foreach 1..1000; |
$sum += 1 / $_ ** 2 foreach 1..1000; |
||
print "$sum\n";</ |
print "$sum\n";</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="perl">use List::Util qw(reduce); |
||
$sum = reduce { $a + 1 / $b ** 2 } 0, 1..1000; |
$sum = reduce { $a + 1 / $b ** 2 } 0, 1..1000; |
||
print "$sum\n";</ |
print "$sum\n";</syntaxhighlight> |
||
An other way of doing it is to define the series as a closure: |
An other way of doing it is to define the series as a closure: |
||
< |
<syntaxhighlight lang="perl">my $S = do { my ($sum, $k); sub { $sum += 1/++$k**2 } }; |
||
my @S = map &$S, 1 .. 1000; |
my @S = map &$S, 1 .. 1000; |
||
print $S[-1];</ |
print $S[-1];</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">sumto</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">sumto</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> |
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> |
||
Line 2,009: | Line 2,363: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #000000;">sumto</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?</span><span style="color: #000000;">sumto</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,016: | Line 2,370: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
/** |
/** |
||
Line 2,038: | Line 2,392: | ||
echo sum_of_a_series(1000,1); |
echo sum_of_a_series(1000,1); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>1.6439345666816</pre> |
<pre>1.6439345666816</pre> |
||
=={{header|Picat}}== |
|||
===List comprehension=== |
|||
<syntaxhighlight lang="picat">s(N) = sum([1.0/K**2 : K in 1..N]).</syntaxhighlight> |
|||
===Iterative=== |
|||
<syntaxhighlight lang="picat">s2(N) = Sum => |
|||
K = 1, |
|||
Sum1 = 0, |
|||
while(K <= N) |
|||
Sum1 := Sum1 + 1/K**2, |
|||
K := K + 1 |
|||
end, |
|||
Sum = Sum1.</syntaxhighlight> |
|||
===Test=== |
|||
<syntaxhighlight lang="picat">go => |
|||
% List comprehension |
|||
test(s,1000), |
|||
nl, |
|||
% Iterative |
|||
test(s2,1000), |
|||
nl. |
|||
test(Fun,N) => |
|||
println([fun=Fun,n=N]), |
|||
Pi2_6 = math.pi**2/6, |
|||
println(Pi2_6='math.pi**2/6'), |
|||
nl, |
|||
foreach(I in 1..6) |
|||
S = apply(Fun,10**I), |
|||
printf("%f (diff: %w)\n", S,Pi2_6-S) |
|||
end, |
|||
nl.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[fun = s,n = 1000] |
|||
1.644934066848226 = math.pi**2/6 |
|||
1.549768 (diff: 0.095166335681686) |
|||
1.634984 (diff: 0.009950166663334) |
|||
1.643935 (diff: 0.000999500166665) |
|||
1.644834 (diff: 0.000099995000161) |
|||
1.644924 (diff: 0.000009999949984) |
|||
1.644933 (diff: 0.000000999999456) |
|||
[fun = s2,n = 1000] |
|||
1.644934066848226 = math.pi**2/6 |
|||
1.549768 (diff: 0.095166335681686) |
|||
1.634984 (diff: 0.009950166663334) |
|||
1.643935 (diff: 0.000999500166665) |
|||
1.644834 (diff: 0.000099995000161) |
|||
1.644924 (diff: 0.000009999949984) |
|||
1.644933 (diff: 0.000000999999456)</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(scl 9) # Calculate with 9 digits precision |
||
(let S 0 |
(let S 0 |
||
(for I 1000 |
(for I 1000 |
||
(inc 'S (*/ 1.0 (* I I))) ) |
(inc 'S (*/ 1.0 (* I I))) ) |
||
(prinl (round S 6)) ) # Round result to 6 digits</ |
(prinl (round S 6)) ) # Round result to 6 digits</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>1.643935</pre> |
<pre>1.643935</pre> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">array(int) x = enumerate(1000,1,1); |
||
`+(@(1.0/pow(x[*],2)[*])); |
`+(@(1.0/pow(x[*],2)[*])); |
||
Result: 1.64393</ |
Result: 1.64393</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">/* sum the first 1000 terms of the series 1/n**2. */ |
||
s = 0; |
s = 0; |
||
Line 2,065: | Line 2,474: | ||
end; |
end; |
||
put skip list (s);</ |
put skip list (s);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,074: | Line 2,483: | ||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">lvars s = 0, j; |
||
for j from 1 to 1000 do |
for j from 1 to 1000 do |
||
s + 1.0/(j*j) -> s; |
s + 1.0/(j*j) -> s; |
||
endfor; |
endfor; |
||
s =></ |
s =></syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
/aproxriemann{ |
/aproxriemann{ |
||
/x exch def |
/x exch def |
||
Line 2,095: | Line 2,504: | ||
1000 aproxriemann |
1000 aproxriemann |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
1.64393485 |
1.64393485 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<syntaxhighlight lang="postscript"> |
||
% using map |
% using map |
||
[1 1000] 1 range {dup * 1 exch div} map 0 {+} fold |
[1 1000] 1 range {dup * 1 exch div} map 0 {+} fold |
||
Line 2,108: | Line 2,517: | ||
% just using fold |
% just using fold |
||
[1 1000] 1 range 0 {dup * 1 exch div +} fold |
[1 1000] 1 range 0 {dup * 1 exch div +} fold |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Potion}}== |
=={{header|Potion}}== |
||
< |
<syntaxhighlight lang="potion">sum = 0.0 |
||
1 to 1000 (i): sum = sum + 1.0 / (i * i). |
1 to 1000 (i): sum = sum + 1.0 / (i * i). |
||
sum print</ |
sum print</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">$x = 1..1000 ` |
||
| ForEach-Object { 1 / ($_ * $_) } ` |
| ForEach-Object { 1 / ($_ * $_) } ` |
||
| Measure-Object -Sum |
| Measure-Object -Sum |
||
Write-Host Sum = $x.Sum</ |
Write-Host Sum = $x.Sum</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog. |
Works with SWI-Prolog. |
||
< |
<syntaxhighlight lang="prolog">sum(S) :- |
||
findall(L, (between(1,1000,N),L is 1/N^2), Ls), |
findall(L, (between(1,1000,N),L is 1/N^2), Ls), |
||
sumlist(Ls, S). |
sumlist(Ls, S). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Ouptput : |
Ouptput : |
||
<pre>?- sum(S). |
<pre>?- sum(S). |
||
Line 2,133: | Line 2,542: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Define i, sum.d |
||
For i=1 To 1000 |
For i=1 To 1000 |
||
Line 2,139: | Line 2,548: | ||
Next i |
Next i |
||
Debug sum</ |
Debug sum</syntaxhighlight> |
||
<tt> |
<tt> |
||
Answer = 1.6439345666815615 |
Answer = 1.6439345666815615 |
||
Line 2,145: | Line 2,554: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">print ( sum(1.0 / (x * x) for x in range(1, 1001)) )</syntaxhighlight> |
||
Or, as a generalised map, or fold / reduction – (see [[Catamorphism#Python]]): |
Or, as a generalised map, or fold / reduction – (see [[Catamorphism#Python]]): |
||
< |
<syntaxhighlight lang="python">'''The sum of a series''' |
||
from functools import reduce |
from functools import reduce |
||
Line 2,220: | Line 2,629: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>The sum of a series: |
<pre>The sum of a series: |
||
Line 2,228: | Line 2,637: | ||
=={{header|Q}}== |
=={{header|Q}}== |
||
< |
<syntaxhighlight lang="q">sn:{sum xexp[;-2] 1+til x} |
||
sn 1000</ |
sn 1000</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,238: | Line 2,647: | ||
Using the Quackery bignum rational arithmetic suite <code>bigrat.qky</code>. |
Using the Quackery bignum rational arithmetic suite <code>bigrat.qky</code>. |
||
< |
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now! |
||
[ 0 n->v rot times |
[ 0 n->v rot times |
||
Line 2,255: | Line 2,664: | ||
say "As a decimal fraction, first 1000 places after the decimal point." |
say "As a decimal fraction, first 1000 places after the decimal point." |
||
cr cr |
cr cr |
||
1000 point$ echo$</ |
1000 point$ echo$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,270: | Line 2,679: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">print( sum( 1/seq(1000)^2 ) )</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 2,276: | Line 2,685: | ||
A solution using Typed Racket: |
A solution using Typed Racket: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang typed/racket |
#lang typed/racket |
||
Line 2,283: | Line 2,692: | ||
(for/sum: : Real ([k : Natural (in-range 1 (+ n 1))]) |
(for/sum: : Real ([k : Natural (in-range 1 (+ n 1))]) |
||
(/ 1.0 (* k k)))) |
(/ 1.0 (* k k)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 2,291: | Line 2,700: | ||
In general, the <code>$n</code>th partial sum of a series whose terms are given by a unary function <code>&f</code> is |
In general, the <code>$n</code>th partial sum of a series whose terms are given by a unary function <code>&f</code> is |
||
<lang |
<syntaxhighlight lang="raku" line>[+] map &f, 1 .. $n</syntaxhighlight> |
||
So what's needed in this case is |
So what's needed in this case is |
||
<lang |
<syntaxhighlight lang="raku" line>say [+] map { 1 / $^n**2 }, 1 .. 1000;</syntaxhighlight> |
||
Or, using the "hyper" metaoperator to vectorize, we can use a more "point free" style while keeping traditional precedence: |
Or, using the "hyper" metaoperator to vectorize, we can use a more "point free" style while keeping traditional precedence: |
||
<lang |
<syntaxhighlight lang="raku" line>say [+] 1 «/« (1..1000) »**» 2;</syntaxhighlight> |
||
Or we can use the <tt>X</tt> "cross" metaoperator, which is convenient even if one side or the other is a scalar. In this case, we demonstrate a scalar on either side: |
Or we can use the <tt>X</tt> "cross" metaoperator, which is convenient even if one side or the other is a scalar. In this case, we demonstrate a scalar on either side: |
||
<lang |
<syntaxhighlight lang="raku" line>say [+] 1 X/ (1..1000 X** 2);</syntaxhighlight> |
||
Note that cross ops are parsed as list infix precedence rather than using the precedence of the base op as hypers do. Hence the difference in parenthesization. |
Note that cross ops are parsed as list infix precedence rather than using the precedence of the base op as hypers do. Hence the difference in parenthesization. |
||
With list comprehensions, you can write: |
With list comprehensions, you can write: |
||
<lang |
<syntaxhighlight lang="raku" line>say [+] (1 / $_**2 for 1..1000);</syntaxhighlight> |
||
That's fine for a single result, but if you're going to be evaluating the sequence multiple times, you don't want to be recalculating the sum each time, so it's more efficient to define the sequence as a constant to let the run-time automatically cache those values already calculated. In a lazy language like Raku, it's generally considered a stronger abstraction to write the correct infinite sequence, and then take the part of it you're interested in. |
That's fine for a single result, but if you're going to be evaluating the sequence multiple times, you don't want to be recalculating the sum each time, so it's more efficient to define the sequence as a constant to let the run-time automatically cache those values already calculated. In a lazy language like Raku, it's generally considered a stronger abstraction to write the correct infinite sequence, and then take the part of it you're interested in. |
||
Here we define an infinite sequence of partial sums (by adding a backslash into the reduction to make it look "triangular"), then take the 1000th term of that: |
Here we define an infinite sequence of partial sums (by adding a backslash into the reduction to make it look "triangular"), then take the 1000th term of that: |
||
<lang |
<syntaxhighlight lang="raku" line>constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *; |
||
say @x[1000]; # prints 1.64393456668156</ |
say @x[1000]; # prints 1.64393456668156</syntaxhighlight> |
||
Note that infinite constant sequences can be lazily generated in Raku, or this wouldn't work so well... |
Note that infinite constant sequences can be lazily generated in Raku, or this wouldn't work so well... |
||
A cleaner style is to combine these approaches with a more FP look: |
A cleaner style is to combine these approaches with a more FP look: |
||
<lang |
<syntaxhighlight lang="raku" line>constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*; |
||
say ζish[1000];</ |
say ζish[1000];</syntaxhighlight> |
||
Perhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization: |
Perhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization: |
||
<lang |
<syntaxhighlight lang="raku" line>use experimental :cached; |
||
sub ζ($s) is cached { [\+] 1..* X** -$s } |
sub ζ($s) is cached { [\+] 1..* X** -$s } |
||
say ζ(2)[1000];</ |
say ζ(2)[1000];</syntaxhighlight> |
||
Notice how the thus-defined zeta function returns a lazy list of approximated values, which is arguably the closest we can get from the mathematical definition. |
Notice how the thus-defined zeta function returns a lazy list of approximated values, which is arguably the closest we can get from the mathematical definition. |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">0 1 1000 1 range each 1.0 swap dup * / + |
||
"%g\n" print</ |
"%g\n" print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.64393</pre> |
<pre>1.64393</pre> |
||
Line 2,335: | Line 2,744: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">Red [] |
||
s: 0 |
s: 0 |
||
repeat n 1000 [ s: 1.0 / n ** 2 + s ] |
repeat n 1000 [ s: 1.0 / n ** 2 + s ] |
||
print s |
print s |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===sums specific terms=== |
===sums specific terms=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */ |
||
parse arg N D . /*obtain optional arguments from the CL*/ |
parse arg N D . /*obtain optional arguments from the CL*/ |
||
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
||
Line 2,353: | Line 2,762: | ||
end /*k*/ |
end /*k*/ |
||
say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */</ |
say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' when using the default input: |
'''output''' when using the default input: |
||
<pre> |
<pre> |
||
Line 2,361: | Line 2,770: | ||
===sums with running total=== |
===sums with running total=== |
||
This REXX version shows the ''running total'' for every 10<sup>th</sup> term. |
This REXX version shows the ''running total'' for every 10<sup>th</sup> term. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sums the first N terms o f 1/(k**2), k=1 ──► N. */ |
||
parse arg N D . /*obtain optional arguments from the CL*/ |
parse arg N D . /*obtain optional arguments from the CL*/ |
||
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
||
Line 2,379: | Line 2,788: | ||
say /*a blank line for sep. */ |
say /*a blank line for sep. */ |
||
say 'The sum of' right(k-1,w) "terms is:" $ /*display the final sum.*/ |
say 'The sum of' right(k-1,w) "terms is:" $ /*display the final sum.*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' when using the input of: <tt> 1000000000 </tt> |
'''output''' when using the input of: <tt> 1000000000 </tt> |
||
<pre> |
<pre> |
||
Line 2,402: | Line 2,811: | ||
If the '''old''' REXX variable would be set to '''1.64''' (instead of '''1'''), the first noise digits could be bypassed to make the display ''cleaner''. |
If the '''old''' REXX variable would be set to '''1.64''' (instead of '''1'''), the first noise digits could be bypassed to make the display ''cleaner''. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */ |
||
parse arg N D . /*obtain optional arguments from the CL*/ |
parse arg N D . /*obtain optional arguments from the CL*/ |
||
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/ |
||
Line 2,422: | Line 2,831: | ||
say /*display blank line for the separator.*/ |
say /*display blank line for the separator.*/ |
||
say 'The sum of' right(N,w) "terms is:" /*display the sum's preamble line. */ |
say 'The sum of' right(N,w) "terms is:" /*display the sum's preamble line. */ |
||
say $ /*stick a fork in it, we're all done. */</ |
say $ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' when using the input of (one billion [limit], and one hundred decimal digits): <tt> 1000000000 100 </tt> |
'''output''' when using the input of (one billion [limit], and one hundred decimal digits): <tt> 1000000000 100 </tt> |
||
<pre> |
<pre> |
||
Line 2,450: | Line 2,859: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
<syntaxhighlight lang="ring"> |
|||
<lang Ring> |
|||
sum = 0 |
sum = 0 |
||
for i =1 to 1000 |
for i =1 to 1000 |
||
Line 2,457: | Line 2,866: | ||
decimals(8) |
decimals(8) |
||
see sum |
see sum |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6 |
>> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6 |
||
-0.000999500167 |
-0.000999500167 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
≪ 0 1 ROT '''FOR''' k SQ INV + '''NEXT''' ≫ '<span style="color:blue">∑INV2</span>'''' STO |
|||
1000 <span style="color:blue">∑INV2</span> |
|||
The emulator immediately returns |
|||
1: 1.64393456668 |
|||
A basic HP-28S calculator returns after 27.5 seconds |
|||
1: 1.64393456674 |
|||
{{works with|HP|49}} |
|||
'k' 1 1000 '1/SQ(k)' ∑ |
|||
returns in 2 minutes 27 seconds, with exact mode set: |
|||
1: 83545938483149689478187854264854884386044454314086472930763839512603803291207881839588904977469387999844962675327115010933903589145654299730231109091124308462732153297321867661093162618281746011828755017021645889046777854795025297006943669294330752479399654716368801794529682603741344724733173765262964463970763934463926259796895140901128384286333311745462863716753134735154188954742414035836608258393970996630553795415075904205673610359458498106833291961256452756993199997231825920203667952667546787052535763624910912251107083702817265087341966845358732584971361645348091123849687614886682117125784781422103460192439394780707024963279033532646857677925648889105430050030795563141941157379481719403833258405980463950499887302926152552848089894630843538497552630691676216896740675701385847032173192623833881016332493844186817408141003602396236858699094240207812766449 / 50820720104325812617835292273000760481839790754374852703215456050992581046448162621598030244504097240825920773913981926305208272518886258627010933716354037062979680120674828102224650586465553482032614190502746121717248161892239954030493982549422690846180552358769564169076876408783086920322038142618269982747137757706040198826719424371333781947889528085329853597116893889786983109597085041878513917342099206896166585859839289193299599163669641323895022932959750057616390808553697984192067774252834860398458100840611325353202165675189472559524948330224159123505567527375848194800452556940453530457590024173749704941834382709198515664897344438584947842793131829050180589581507273988682409028088248800576590497216884808783192565859896957125449502802395453976401743504938336291933628859306247684023233969172475385327442707968328512729836445886537101453118476390400000000 |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">puts (1..1000).sum{ |x| 1r / x ** 2 }.to_f</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,473: | Line 2,895: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic"> |
||
for i =1 to 1000 |
for i =1 to 1000 |
||
sum = sum + 1 /( i^2) |
sum = sum + 1 /( i^2) |
||
next i |
next i |
||
print sum</ |
print sum</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">const LOWER: i32 = 1; |
||
const UPPER: i32 = 1000; |
const UPPER: i32 = 1000; |
||
Line 2,492: | Line 2,914: | ||
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x)); |
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">data _null_; |
||
s=0; |
s=0; |
||
do n=1 to 1000; |
do n=1 to 1000; |
||
Line 2,502: | Line 2,924: | ||
e=s-constant('pi')**2/6; |
e=s-constant('pi')**2/6; |
||
put s e; |
put s e; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">scala> 1 to 1000 map (x => 1.0 / (x * x)) sum |
||
res30: Double = 1.6439345666815615</ |
res30: Double = 1.6439345666815615</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (sum a b fn) |
||
(do ((i a (+ i 1)) |
(do ((i a (+ i 1)) |
||
(result 0 (+ result (fn i)))) |
(result 0 (+ result (fn i)))) |
||
Line 2,515: | Line 2,937: | ||
(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction |
(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction |
||
(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal</ |
(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal</syntaxhighlight> |
||
More idiomatic way (or so they say) by tail recursion: |
More idiomatic way (or so they say) by tail recursion: |
||
< |
<syntaxhighlight lang="scheme">(define (invsq f to) |
||
(let loop ((f f) (s 0)) |
(let loop ((f f) (s 0)) |
||
(if (> f to) |
(if (> f to) |
||
Line 2,526: | Line 2,948: | ||
;; whether you get a rational or a float depends on implementation |
;; whether you get a rational or a float depends on implementation |
||
(invsq 1 1000) ; 835459384831...766449/50820...90400000000 |
(invsq 1 1000) ; 835459384831...766449/50820...90400000000 |
||
(exact->inexact (invsq 1 1000)) ; 1.64393456668156</ |
(exact->inexact (invsq 1 1000)) ; 1.64393456668156</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 2,544: | Line 2,966: | ||
end for; |
end for; |
||
writeln(sum digits 6 lpad 8); |
writeln(sum digits 6 lpad 8); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SETL}}== |
|||
<syntaxhighlight lang="setl">print( +/[1/k**2 : k in [1..1000]] );</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1.64393456668156</pre> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">say sum(1..1000, {|n| 1 / n**2 })</syntaxhighlight> |
||
Alternatively, using the ''reduce{}'' method: |
Alternatively, using the ''reduce{}'' method: |
||
< |
<syntaxhighlight lang="ruby">say (1..1000 -> reduce { |a,b| a + (1 / b**2) })</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,561: | Line 2,988: | ||
Manually coerce it to a float, otherwise you will get an exact (and slow) answer: |
Manually coerce it to a float, otherwise you will get an exact (and slow) answer: |
||
< |
<syntaxhighlight lang="slate">((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">( (1 to: 1000) fold: [:sum :aNumber | |
||
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.</ |
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.</syntaxhighlight> |
||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "sumseries" ) |
|||
@( description, "Compute the nth term of a series, i.e. the " ) |
|||
@( description, "sum of the n first terms of the " ) |
|||
@( description, "corresponding sequence. For this task " ) |
|||
@( description, "repeat 1000 times. " ) |
|||
@( see_also, "http://rosettacode.org/wiki/Sum_of_a_series" ) |
|||
@( author, "Ken O. Burtch" ); |
|||
pragma license( unrestricted ); |
|||
pragma restriction( no_external_commands ); |
|||
procedure sumseries is |
|||
function inverse_square( x : long_float ) return long_float is |
|||
begin |
|||
return 1/x**2; |
|||
end inverse_square; |
|||
total : long_float := 0.0; |
|||
max_param : constant natural := 1000; |
|||
begin |
|||
for i in 1..max_param loop |
|||
total := @ + inverse_square( i ); |
|||
end loop; |
|||
put( "Sum of F(x) from 1 to" ) |
|||
@( max_param ) |
|||
@( " is" ) |
|||
@( total ); |
|||
new_line; |
|||
end sumseries;</syntaxhighlight> |
|||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
< |
<syntaxhighlight lang="sql">create table t1 (n real); |
||
-- this is postgresql specific, fill the table |
-- this is postgresql specific, fill the table |
||
insert into t1 (select generate_series(1,1000)::real); |
insert into t1 (select generate_series(1,1000)::real); |
||
Line 2,574: | Line 3,037: | ||
select 1/(n*n) as recip from t1 |
select 1/(n*n) as recip from t1 |
||
) select sum(recip) from tt; |
) select sum(recip) from tt; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Result of select (with locale DE): |
Result of select (with locale DE): |
||
<pre> |
<pre> |
||
Line 2,584: | Line 3,047: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">function series(n) { |
||
return(sum((n..1):^-2)) |
return(sum((n..1):^-2)) |
||
} |
} |
||
series(1000)-pi()^2/6 |
series(1000)-pi()^2/6 |
||
-.0009995002</ |
-.0009995002</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
<syntaxhighlight lang="swift"> |
|||
<lang Swift> |
|||
func sumSeries(var n: Int) -> Double { |
func sumSeries(var n: Int) -> Double { |
||
var ret: Double = 0 |
var ret: Double = 0 |
||
Line 2,604: | Line 3,067: | ||
output: 1.64393456668156 |
output: 1.64393456668156 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<lang> |
<syntaxhighlight lang="text"> |
||
Swift also allows extension to datatypes. Here's similar code using an extension to Int. |
Swift also allows extension to datatypes. Here's similar code using an extension to Int. |
||
Line 2,629: | Line 3,092: | ||
y = 1000.sumSeries() |
y = 1000.sumSeries() |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 2,635: | Line 3,098: | ||
=== Using Expansion Operator and mathop === |
=== Using Expansion Operator and mathop === |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
namespace path {::tcl::mathop ::tcl::} ;# Ease of access to mathop commands |
namespace path {::tcl::mathop ::tcl::} ;# Ease of access to mathop commands |
||
proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} ;# an expr would be clearer, but this is a demonstration of mathop |
proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} ;# an expr would be clearer, but this is a demonstration of mathop |
||
# using range function defined below |
# using range function defined below |
||
lsum_series [range 1 1001] ;# ==> 1.6439345666815615</ |
lsum_series [range 1 1001] ;# ==> 1.6439345666815615</syntaxhighlight> |
||
=== Using Loop === |
=== Using Loop === |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc partial_sum {func - start - stop} { |
proc partial_sum {func - start - stop} { |
||
Line 2,655: | Line 3,118: | ||
set S {x {expr {1.0 / $x**2}}} |
set S {x {expr {1.0 / $x**2}}} |
||
partial_sum $S from 1 to 1000 ;# => 1.6439345666815615</ |
partial_sum $S from 1 to 1000 ;# => 1.6439345666815615</syntaxhighlight> |
||
=== Using tcllib === |
=== Using tcllib === |
||
{{tcllib|struct::list}} |
{{tcllib|struct::list}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
package require struct::list |
package require struct::list |
||
Line 2,668: | Line 3,131: | ||
set S {x {expr {1.0 / $x**2}}} |
set S {x {expr {1.0 / $x**2}}} |
||
sum_of $S [range 1 1001] ;# ==> 1.6439345666815615</ |
sum_of $S [range 1 1001] ;# ==> 1.6439345666815615</syntaxhighlight> |
||
The helper <code>range</code> procedure is: |
The helper <code>range</code> procedure is: |
||
< |
<syntaxhighlight lang="tcl"># a range command akin to Python's |
||
proc range args { |
proc range args { |
||
foreach {start stop step} [switch -exact -- [llength $args] { |
foreach {start stop step} [switch -exact -- [llength $args] { |
||
Line 2,686: | Line 3,149: | ||
} |
} |
||
return $range |
return $range |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
Line 2,692: | Line 3,155: | ||
{{trans|TI-89 BASIC}} |
{{trans|TI-89 BASIC}} |
||
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}} |
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}} |
||
< |
<syntaxhighlight lang="ti83b"> |
||
∑(1/X²,X,1,1000) |
∑(1/X²,X,1,1000) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,703: | Line 3,166: | ||
The TI-83 does not have the new summation notation, and caps lists at 999 entries. |
The TI-83 does not have the new summation notation, and caps lists at 999 entries. |
||
< |
<syntaxhighlight lang="ti83b">sum(seq(1/X²,X,1,999))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,711: | Line 3,174: | ||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
< |
<syntaxhighlight lang="ti89b">∑(1/x^2,x,1,1000)</syntaxhighlight> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 2,719: | Line 3,182: | ||
Variant A1: limit the list generation inside the <code>gen</code> operator. |
Variant A1: limit the list generation inside the <code>gen</code> operator. |
||
< |
<syntaxhighlight lang="txr">txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]' |
||
1.64393456668156</ |
1.64393456668156</syntaxhighlight> |
||
Variant A2: generate infinite list, but take only the first 1000 items using <code>[list-expr 0..999]</code>. |
Variant A2: generate infinite list, but take only the first 1000 items using <code>[list-expr 0..999]</code>. |
||
< |
<syntaxhighlight lang="txr">txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]' |
||
1.64393456668156</ |
1.64393456668156</syntaxhighlight> |
||
Variant B: generate lazy integer range, and pump it through a series of function with the help of the <code>chain</code> functional combinator and the <code>op</code> partial evaluation/binding operator. |
Variant B: generate lazy integer range, and pump it through a series of function with the help of the <code>chain</code> functional combinator and the <code>op</code> partial evaluation/binding operator. |
||
< |
<syntaxhighlight lang="txr">txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]' |
||
1.64393456668156</ |
1.64393456668156</syntaxhighlight> |
||
Variant C: unravel the chain in Variant B using straightforward nesting. |
Variant C: unravel the chain in Variant B using straightforward nesting. |
||
< |
<syntaxhighlight lang="txr">txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]' |
||
1.64393456668156</ |
1.64393456668156</syntaxhighlight> |
||
Variant D: bring Variant B's inverse square calculation into the fold, eliminating mapcar. Final answer. |
Variant D: bring Variant B's inverse square calculation into the fold, eliminating mapcar. Final answer. |
||
< |
<syntaxhighlight lang="txr">txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]' |
||
1.64393456668156</ |
1.64393456668156</syntaxhighlight> |
||
=={{header|Unicon}}== |
=={{header|Unicon}}== |
||
Line 2,746: | Line 3,209: | ||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
< |
<syntaxhighlight lang="bash">term() { |
||
b=$1;res=$2 |
b=$1;res=$2 |
||
echo "scale=5;1/($res*$res)+$b" | bc |
echo "scale=5;1/($res*$res)+$b" | bc |
||
Line 2,763: | Line 3,226: | ||
} |
} |
||
(echo 3; echo 1; echo 4) | fold sum</ |
(echo 3; echo 1; echo 4) | fold sum</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 2,771: | Line 3,234: | ||
function, plus. The rest the expression constructs the series |
function, plus. The rest the expression constructs the series |
||
by inverting the square of each number in the list from 1 to 1000. |
by inverting the square of each number in the list from 1 to 1000. |
||
< |
<syntaxhighlight lang="ursala">#import flo |
||
#import nat |
#import nat |
||
#cast %e |
#cast %e |
||
total = plus:-0 div/*1. sqr* float*t iota 1001</ |
total = plus:-0 div/*1. sqr* float*t iota 1001</syntaxhighlight> |
||
output: |
output: |
||
<pre>1.643935e+00</pre> |
<pre>1.643935e+00</pre> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala"> |
||
public static void main(){ |
public static void main(){ |
||
int i, start = 1, end = 1000; |
int i, start = 1, end = 1000; |
||
Line 2,791: | Line 3,254: | ||
stdout.printf("%s\n", sum.to_string()); |
stdout.printf("%s\n", sum.to_string()); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 2,799: | Line 3,262: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Private Function sumto(n As Integer) As Double |
||
Dim res As Double |
Dim res As Double |
||
For i = 1 To n |
For i = 1 To n |
||
Line 2,808: | Line 3,271: | ||
Public Sub main() |
Public Sub main() |
||
Debug.Print sumto(1000) |
Debug.Print sumto(1000) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre> 1,64393456668156 </pre> |
<pre> 1,64393456668156 </pre> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">' Sum of a series |
||
for i=1 to 1000 |
for i=1 to 1000 |
||
s=s+1/i^2 |
s=s+1/i^2 |
||
next |
next |
||
wscript.echo s </ |
wscript.echo s </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,825: | Line 3,288: | ||
{{trans|VBScript}} |
{{trans|VBScript}} |
||
{{works with|Visual Basic .NET|2013}} |
{{works with|Visual Basic .NET|2013}} |
||
< |
<syntaxhighlight lang="vbnet">' Sum of a series |
||
Sub SumOfaSeries() |
Sub SumOfaSeries() |
||
Dim s As Double |
Dim s As Double |
||
Line 2,833: | Line 3,296: | ||
Next 'i |
Next 'i |
||
Console.WriteLine(s) |
Console.WriteLine(s) |
||
End Sub </ |
End Sub </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
1.64393456668156 |
1.64393456668156 |
||
</pre> |
</pre> |
||
=={{header|Verilog}}== |
|||
<syntaxhighlight lang="Verilog">module main; |
|||
integer i; |
|||
real sum; |
|||
initial begin |
|||
sum = 0.0; |
|||
for(i = 1; i <= 1000; i=i+1) sum = sum + 1.0 / (i * i); |
|||
$display(sum); |
|||
end |
|||
endmodule</syntaxhighlight> |
|||
<pre>1.64393</pre> |
|||
=={{header|V (Vlang)}}== |
|||
{{trans|go}} |
|||
<syntaxhighlight lang="v (vlang)">import math |
|||
fn main(){ |
|||
println('known: ${math.pi*math.pi/6}') |
|||
mut sum := f64(0) |
|||
for i :=1e3; i >0; i-- { |
|||
sum += 1/(i*i) |
|||
} |
|||
println('computed: $sum') |
|||
}</syntaxhighlight> |
|||
Output: |
|||
<pre>known: 1.6449340668482264 |
|||
computed: 1.6439345666815597</pre> |
|||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang="wdte">let s => import 'stream'; |
||
s.range 1 1001 |
s.range 1 1001 |
||
Line 2,846: | Line 3,338: | ||
-> s.reduce 0 + |
-> s.reduce 0 + |
||
-- io.writeln io.stdout |
-- io.writeln io.stdout |
||
;</ |
;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,852: | Line 3,344: | ||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@sum !*#~V1Sn @to 1000 ; returns 1.6439345666815615</syntaxhighlight> |
||
< |
<syntaxhighlight lang="wortel">@to 1000 ; generates a list of 1 to 1000 (inclusive) |
||
#~V1Sn ; number expression which stands for: square push(1) swap divide |
#~V1Sn ; number expression which stands for: square push(1) swap divide |
||
!* ; maps the number expression over the list |
!* ; maps the number expression over the list |
||
@sum ; sums the list</ |
@sum ; sums the list</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">var sumSeries = Fn.new { |n| (1..n).reduce(0) { |sum, i| sum + 1/(i*i) } } |
||
System.print("s(1000) = %(sumSeries.call(1000))") |
System.print("s(1000) = %(sumSeries.call(1000))") |
||
System.print("zeta(2) = %(Num.pi*Num.pi/6)")</ |
System.print("zeta(2) = %(Num.pi*Num.pi/6)")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,871: | Line 3,363: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code CrLf=9; code real RlOut=48; |
||
int X; real S; |
int X; real S; |
||
[S:= 0.0; |
[S:= 0.0; |
||
for X:= 1 to 1000 do S:= S + 1.0/float(X*X); |
for X:= 1 to 1000 do S:= S + 1.0/float(X*X); |
||
RlOut(0, S); CrLf(0); |
RlOut(0, S); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,884: | Line 3,376: | ||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">(1./indgen(1:1000)^2)(sum)</syntaxhighlight> |
||
=={{header|Zig}}== |
|||
{{Works with|Zig|0.11.0}} |
|||
<syntaxhighlight lang="zig">const std = @import("std"); |
|||
fn f(x: u64) f64 { |
|||
return 1 / @as(f64, @floatFromInt(x * x)); |
|||
} |
|||
fn sum(comptime func: fn (u64) f64, n: u64) f64 { |
|||
var s: f64 = 0.0; |
|||
var i: u64 = n; |
|||
while (i != 0) : (i -= 1) |
|||
s += func(i); |
|||
return s; |
|||
} |
|||
pub fn main() !void { |
|||
const stdout = std.io.getStdOut().writer(); |
|||
try stdout.print("S_1000 = {d:.15}\n", .{sum(f, 1000)}); |
|||
}</syntaxhighlight>{{out}} |
|||
<pre>S_1000 = 1.643934566681560</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">[1.0..1000].reduce(fcn(p,n){ p + 1.0/(n*n) },0.0) //-->1.64394</syntaxhighlight> |
||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
< |
<syntaxhighlight lang="zxbasic">10 LET n=1000 |
||
20 LET s=0 |
20 LET s=0 |
||
30 FOR k=1 TO n |
30 FOR k=1 TO n |
||
40 LET s=s+1/(k*k) |
40 LET s=s+1/(k*k) |
||
50 NEXT k |
50 NEXT k |
||
60 PRINT s</ |
60 PRINT s</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 19:36, 1 May 2024
You are encouraged to solve this task according to the task description, using any language you may know.
Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
- and compute
This approximates the zeta function for S=2, whose exact value
is the solution of the Basel problem.
11l
print(sum((1..1000).map(x -> 1.0/x^2)))
- Output:
1.64393
360 Assembly
* Sum of a series 30/03/2017
SUMSER CSECT
USING SUMSER,12 base register
LR 12,15 set addressability
LR 10,14 save r14
LE 4,=E'0' s=0
LE 2,=E'1' i=1
DO WHILE=(CE,2,LE,=E'1000') do i=1 to 1000
LER 0,2 i
MER 0,2 *i
LE 6,=E'1' 1
DER 6,0 1/i**2
AER 4,6 s=s+1/i**2
AE 2,=E'1' i=i+1
ENDDO , enddo i
LA 0,4 format F13.4
LER 0,4 s
BAL 14,FORMATF call formatf
MVC PG(13),0(1) retrieve result
XPRNT PG,80 print buffer
BR 10 exit
COPY FORMATF formatf code
PG DC CL80' ' buffer
END SUMSER
- Output:
1.6439
ACL2
(defun sum-x^-2 (max-x)
(if (zp max-x)
0
(+ (/ (* max-x max-x))
(sum-x^-2 (1- max-x)))))
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Calc(CARD n REAL POINTER res)
CARD i,st
BYTE perc
REAL one,a,b
IntToReal(0,res)
IF n=0 THEN RETURN FI
IntToReal(1,one)
st=n/100
FOR i=1 TO n
DO
IF i MOD st=0 THEN
PrintB(perc) Put('%) PutE() Put(28)
perc==+1
FI
IntToReal(i,a)
RealMult(a,a,b)
RealDiv(one,b,a)
RealAdd(res,a,b)
RealAssign(b,res)
OD
RETURN
PROC Main()
REAL POINTER res
CARD n=[1000]
Put(125) PutE() ;clear screen
Calc(n,res)
PrintF("s(%U)=",n)
PrintRE(res)
RETURN
- Output:
Screenshot from Atari 8-bit computer
s(1000)=1.64392967
ActionScript
function partialSum(n:uint):Number
{
var sum:Number = 0;
for(var i:uint = 1; i <= n; i++)
sum += 1/(i*i);
return sum;
}
trace(partialSum(1000));
Ada
with Ada.Text_Io; use Ada.Text_Io;
procedure Sum_Series is
function F(X : Long_Float) return Long_Float is
begin
return 1.0 / X**2;
end F;
package Lf_Io is new Ada.Text_Io.Float_Io(Long_Float);
use Lf_Io;
Sum : Long_Float := 0.0;
subtype Param_Range is Integer range 1..1000;
begin
for I in Param_Range loop
Sum := Sum + F(Long_Float(I));
end loop;
Put("Sum of F(x) from" & Integer'Image(Param_Range'First) &
" to" & Integer'Image(Param_Range'Last) & " is ");
Put(Item => Sum, Aft => 10, Exp => 0);
New_Line;
end Sum_Series;
Aime
real
Invsqr(real n)
{
1 / (n * n);
}
integer
main(void)
{
integer i;
real sum;
sum = 0;
i = 1;
while (i < 1000) {
sum += Invsqr(i);
i += 1;
}
o_real(14, sum);
o_byte('\n');
0;
}
ALGOL 68
MODE RANGE = STRUCT(INT lwb, upb);
PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:(
LONG REAL sum := LENG 0.0;
FOR i FROM lwb OF range TO upb OF range DO
sum := sum + f(i)
OD;
sum
);
test:(
RANGE range = (1,1000);
PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2;
print(("Sum of f(x) from ", whole(lwb OF range, 0), " to ",whole(upb OF range, 0)," is ", fixed(SHORTEN sum(f,range),-8,5),".", new line))
)
Output:
Sum of f(x) from 1 to 1000 is 1.64393.
ALGOL W
Uses Jensen's Device (first introduced in Algol 60) which uses call by name to allow a summation index and the expression to sum to be specified as parameters to a summation procedure.
begin % compute the sum of 1/k^2 for k = 1..1000 %
integer k;
% computes the sum of a series from lo to hi using Jensen's Device %
real procedure sum ( integer %name% k; integer value lo, hi; real procedure term );
begin
real temp;
temp := 0;
k := lo;
while k <= hi do begin
temp := temp + term;
k := k + 1
end while_k_le_temp;
temp
end;
write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) )
end.
- Output:
1.64393
APL
+/÷2*⍨⍳1000
1.64393
AppleScript
----------------------- SUM OF SERIES ----------------------
-- seriesSum :: Num a => (a -> a) -> [a] -> a
on seriesSum(f, xs)
script go
property mf : |λ| of mReturn(f)
on |λ|(a, x)
a + mf(x)
end |λ|
end script
foldl(go, 0, xs)
end seriesSum
---------------------------- TEST --------------------------
-- inverseSquare :: Num -> Num
on inverseSquare(x)
1 / (x ^ 2)
end inverseSquare
on run
seriesSum(inverseSquare, enumFromTo(1, 1000))
--> 1.643934566682
end run
--------------------- GENERIC FUNCTIONS --------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
1.643934566682
Arturo
series: map 1..1000 => [1.0/&^2]
print [sum series]
- Output:
1.643934566681561
Asymptote
real sum;
for(int i = 1; i < 1000; ++i) sum = sum + 1 / (i * i);
write(sum, suffix=none);
- Output:
1.64393356668156
AutoHotkey
AutoHotkey allows the precision of floating point numbers generated by math operations to be adjusted via the SetFormat command. The default is 6 decimal places.
SetFormat, FloatFast, 0.15
While A_Index <= 1000
sum += 1/A_Index**2
MsgBox,% sum ;1.643934566681554
AWK
$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}'
1.64393
BASIC
function s(x%)
s = 1 / x ^ 2
end function
function sum(low%, high%)
ret = 0
for i = low to high
ret = ret + s(i)
next i
sum = ret
end function
print sum(1, 1000)
BASIC256
function sumSeries(n)
if n = 0 then sumSeries = 0
let sum = 0
for k = 1 to n
let sum = sum + 1 / k ^ 2
next k
sumSeries = sum
end function
print "s(1000) = "; sumSeries(1000)
print "zeta(2) = "; pi * pi / 6
end
BBC BASIC
FOR i% = 1 TO 1000
sum += 1/i%^2
NEXT
PRINT sum
Gambas
Public Sub Main()
Print "s(1000) = "; sumSeries(1000)
Print "zeta(2) = "; Pi * Pi / 6
End
Function sumSeries(n As Integer) As Float
If n = 0 Then Return 0
Dim sum As Float = 0
For k As Integer = 1 To n
sum += 1.0 / (k * k)
Next
Return sum
End Function
QBasic
FUNCTION sumSeries# (n)
IF n = 0 THEN sunSeries = 0
FOR k = 1 TO n
sum# = sum# + 1! / (k * k)
NEXT
sumSeries# = sum#
END FUNCTION
pi# = 4 * ATN(1)
PRINT "s(1000) = "; sumSeries#(1000)
PRINT "zeta(2) = "; pi# * pi# / 6
END
True BASIC
FUNCTION sumSeries(n)
IF n = 0 then
LET sumSeries = 0
END IF
LET sum = 0
FOR k = 1 to n
LET sum = sum + 1 / k ^ 2
NEXT k
LET sumSeries = sum
END FUNCTION
PRINT "s(1000) = "; sumSeries(1000)
PRINT "zeta(2) = "; pi * pi / 6
END
XBasic
PROGRAM "SumOfASeries"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
DECLARE FUNCTION sumSeries#(n)
FUNCTION Entry ()
pi# = 3.1415926535896
PRINT "s(1000) = "; sumSeries#(1000)
PRINT "zeta(2) = "; pi# * pi# / 6
END FUNCTION
FUNCTION sumSeries#(n)
IF n = 0 THEN RETURN 0
sum# = 0
FOR k = 1 TO n
sum# = sum# + 1.0/(k * k)
NEXT
RETURN sum#
END FUNCTION
END PROGRAM
Yabasic
sub sumSeries(n)
if n = 0 then return 0 : fi
sum = 0
for k = 1 to n
sum = sum + 1 / k ^ 2
next k
return sum
end sub
print "s(1000) = ", sumSeries(1000)
print "zeta(2) = ", pi * pi / 6
end
bc
define f(x) {
return(1 / (x * x))
}
define s(n) {
auto i, s
for (i = 1; i <= n; i++) {
s += f(i)
}
return(s)
}
scale = 20
s(1000)
- Output:
1.64393456668155979824
Beads
beads 1 program 'Sum of a series'
calc main_init
var k = 0
loop reps:1000 count:n
k = k + 1/n^2
log to_str(k)
- Output:
1.6439345666815615
Befunge
Emulates fixed point arithmetic with a 32 bit integer so the result is not very accurate.
05558***>::"~"%00p"~"/10p"( }}2"*v
v*8555$_^#!:-1+*"~"g01g00+/*:\***<
<@$_,#!>#:<+*<v+*86%+55:p00<6\0/**
"."\55+%68^>\55+/00g1-:#^_$
- Output:
1.643934
BQN
√⁼
here reads as the inverse of the square root, which can be changed to 2⋆˜
or ט
. It has been used here since it is the most intuitive.
+´÷√⁼1+↕1000
1.6439345666815597
Bracmat
( 0:?i
& 0:?S
& whl'(1+!i:~>1000:?i&!i^-2+!S:?S)
& out$!S
& out$(flt$(!S,10))
);
Output:
8354593848314...../5082072010432..... (1732 digits and a slash) 1,6439345667*10E0
Brat
p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816
C
#include <stdio.h>
double Invsqr(double n)
{
return 1 / (n*n);
}
int main (int argc, char *argv[])
{
int i, start = 1, end = 1000;
double sum = 0.0;
for( i = start; i <= end; i++)
sum += Invsqr((double)i);
printf("%16.14f\n", sum);
return 0;
}
C#
class Program
{
static void Main(string[] args)
{
// Create and fill a list of number 1 to 1000
List<double> myList = new List<double>();
for (double i = 1; i < 1001; i++)
{
myList.Add(i);
}
// Calculate the sum of 1/x^2
var sum = myList.Sum(x => 1/(x*x));
Console.WriteLine(sum);
Console.ReadLine();
}
}
An alternative approach using Enumerable.Range() to generate the numbers.
class Program
{
static void Main(string[] args)
{
double sum = Enumerable.Range(1, 1000).Sum(x => 1.0 / (x * x));
Console.WriteLine(sum);
Console.ReadLine();
}
}
C++
#include <iostream>
double f(double x);
int main()
{
unsigned int start = 1;
unsigned int end = 1000;
double sum = 0;
for( unsigned int x = start; x <= end; ++x )
{
sum += f(x);
}
std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl;
return 0;
}
double f(double x)
{
return ( 1.0 / ( x * x ) );
}
CLIPS
(deffunction S (?x) (/ 1 (* ?x ?x)))
(deffunction partial-sum-S
(?start ?stop)
(bind ?sum 0)
(loop-for-count (?i ?start ?stop) do
(bind ?sum (+ ?sum (S ?i)))
)
(return ?sum)
)
Usage:
CLIPS> (partial-sum-S 1 1000) 1.64393456668156
Clojure
(reduce + (map #(/ 1.0 % %) (range 1 1001)))
CLU
series_sum = proc (from, to: int,
fn: proctype (real) returns (real))
returns (real)
sum: real := 0.0
for i: int in int$from_to(from, to) do
sum := sum + fn(real$i2r(i))
end
return(sum)
end series_sum
one_over_k_squared = proc (k: real) returns (real)
return(1.0 / (k * k))
end one_over_k_squared
start_up = proc ()
po: stream := stream$primary_output()
result: real := series_sum(1, 1000, one_over_k_squared)
stream$putl(po, f_form(result, 1, 6))
end start_up
- Output:
1.643935
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. sum-of-series.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 N VALUE 1000.
01 series-term USAGE FLOAT-LONG.
01 i PIC 9(4).
PROCEDURE DIVISION.
PERFORM VARYING i FROM 1 BY 1 UNTIL N < i
COMPUTE series-term = series-term + (1 / i ** 2)
END-PERFORM
DISPLAY series-term
GOBACK
.
- Output:
1.643933784000000120
CoffeeScript
console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x)))
Common Lisp
(loop for x from 1 to 1000 summing (expt x -2))
Crystal
puts (1..1000).sum{ |x| 1.0 / x ** 2 }
puts (1..5000).sum{ |x| 1.0 / x ** 2 }
puts (1..9999).sum{ |x| 1.0 / x ** 2 }
puts Math::PI ** 2 / 6
- Output:
1.6439345666815615 1.6447340868469014 1.6448340618480652 1.6449340668482264
D
More Procedural Style
import std.stdio, std.traits;
ReturnType!TF series(TF)(TF func, int end, int start=1)
pure nothrow @safe @nogc {
typeof(return) sum = 0;
foreach (immutable i; start .. end + 1)
sum += func(i);
return sum;
}
void main() {
writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000));
}
- Output:
Sum: 1.64393
More functional Style
Same output.
import std.stdio, std.algorithm, std.range;
enum series(alias F) = (in int end, in int start=1)
pure nothrow @nogc => iota(start, end + 1).map!F.sum;
void main() {
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000));
}
dc
20 k 0 [ln 1 + d sn _2 ^ + 1000 ln <l] d sl x p
- Output:
1.64393456668155979824
Dart
main() {
var list = new List<int>.generate(1000, (i) => i + 1);
num sum = 0;
(list.map((x) => 1.0 / (x * x))).forEach((num e) {
sum += e;
});
print(sum);
}
f(double x) {
if (x == 0)
return x;
else
return (1.0 / (x * x)) + f(x - 1.0);
}
main() {
print(f(1000));
}
Delphi
unit Form_SumOfASeries_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFormSumOfASeries = class(TForm)
M_Log: TMemo;
B_Calc: TButton;
procedure B_CalcClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
FormSumOfASeries: TFormSumOfASeries;
implementation
{$R *.dfm}
function Sum_Of_A_Series(_from,_to:int64):extended;
begin
result:=0;
while _from<=_to do
begin
result:=result+1.0/(_from*_from);
inc(_from);
end;
end;
procedure TFormSumOfASeries.B_CalcClick(Sender: TObject);
begin
try
M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1, 1000)));
except
M_Log.Lines.Add('Error');
end;
end;
end.
- Output:
1.64393456668156
DWScript
var s : Float;
for var i := 1 to 1000 do
s += 1 / Sqr(i);
PrintLn(s);
Dyalect
func Integer.SumSeries() {
var ret = 0
for i in 1..this {
ret += 1 / pow(Float(i), 2)
}
ret
}
var x = 1000
print(x.SumSeries())
- Output:
1.6439345666815615
E
pragma.enable("accumulator")
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }
EasyLang
numfmt 8 0
for i = 1 to 1000
s += 1 / (i * i)
.
print s
EchoLisp
(lib 'math) ;; for (sigma f(n) nfrom nto) function
(Σ (λ(n) (// (* n n))) 1 1000)
;; or
(sigma (lambda(n) (// (* n n))) 1 1000)
→ 1.6439345666815615
(// (* PI PI) 6)
→ 1.6449340668482264
EDSAC order code
Real numbers on EDSAC were restricted to the range -1 <= x < 1. The posted solution cheats slightly by omitting the term with k = 1, while printing '1' before the decimal part. The first eight decimals of the output are correct; the last two should be 67 not 41.
In floating-point arithmetic, summing the smallest terms first is more accurate than summing the largest terms first, as can be seen e.g. in the Pascal solution. EDSAC used fixed-point arithmetic, so the order of summation makes no difference.
[Sum of a series, Rosetta Code website.
EDSAC program, Initial Orders 2.]
..PZ [blank tape and terminator]
[Library subroutine D6 - Division, accurate, fast.
36 locations, working positons 6D and 8D.
C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
T56K
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[Library subroutine P1 - Print positive number, no formatting or round-off.
Prints number in 0D to n places of decimals, where n is specified by 'P n F'
pseudo-order after subroutine call. 21 locations.]
T92K
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Custom subroutine to calculate 1/k^2 for a 17-bit integer k > 1.
Input: 0F = k (with the usual scaling; actually k/(2^16).
Output: 0D = 1/k^2.]
T120K GK
A3F T11@ [set up return to caller as usual]
HF [multiply register := k/(2^16)]
VF [acc := k/(2^16) squared]
[At this point acc =(k^2)/(2^32). Now we switch to 35-bit
arithmetic, in which integers are scaled by 2^(-34)]
R1F [shift acc 2 right to adjust scaling]
T4D [4D := k^2]
TD [set 0D := 0; clears "sandwich bit" between 0F and 1F]
A12@ TF [set 0D := 1 by setting 0F := 1]
A9@ G56F [call EDSAC library subroutine for division]
[11] ZF [overwritten by jump back to caller]
[12] PD [short constant 1]
[Main program]
T200K GK [load at even address because of long variable at 0]
[0] PF PF [build sum here]
[2] PD [short constant 1]
[3] P500F [short constant 1000]
[4] K2048F #F !F @F &F [letters, figures, space, CR, LF]
[9] HF IF LF [letters H, I, L (in letters mode)]
[12] QF MF [digit 1, dot (in figures mode)]
[14] PF [variable k]
[15] T#@ A2@ T14@ [sum := 0, k := 1]
[18] TF A14@ A2@ U14@ TF [inc k; pass new k to function in 0F]
A23@ G120F [call function; places 1/k^2 at 0D]
AD A#@ T#@ [add 1/k^2 into sum]
A14@ S3@ G18@ [test for k = maximum, loop back if not]
O4@ O11@ O89@ O6@ O15@ O89@ O6@ O9@ O10@ O6@ [print 'LO TO HI ']
O5@ O12@ O13@ [print '1.']
A#@ TD A46@ G92F [call subroutine to print decimal part]
P10F [parameter for print subroutine; 10 decimal places]
O7@ O8@ [print CR, LF]
[Sum in reverse order to confirm that the result is identical on EDSAC.
Not much different from the above, so given in condensed form.]
TFT#@A3@T14@TFA14@TFA58@G120FADA#@T#@A14@S2@U14@S2FE55@TDA#@TD
O4@O9@O10@O6@O15@O89@O6@O11@O89@O6@O5@O12@O13@A84@G92FP10FO7@O8@
[89] O5@ ZF [flush teleprinter buffer; stop]
E15Z PF [define entry point; enter with acc = 0]
- Output:
LO TO HI 1.6439345641 HI TO LO 1.6439345641
Eiffel
note
description: "Compute the n-th term of a series"
class
SUM_OF_SERIES_EXAMPLE
inherit
MATH_CONST
create
make
feature -- Initialization
make
local
approximated, known: REAL_64
do
known := Pi^2 / 6
approximated := sum_until (agent g, 1001)
print ("%Nzeta function exact value: %N")
print (known)
print ("%Nzeta function approximated value: %N")
print (approximated)
end
feature -- Access
g (k: INTEGER): REAL_64
-- 'k'-th term of the serie
require
k_positive: k > 0
do
Result := 1 / (k * k)
end
sum_until (s: FUNCTION [ANY, TUPLE [INTEGER], REAL_64]; n: INTEGER): REAL_64
-- sum of the 'n' first terms of 's'
require
n_positive: n > 0
one_parameter: s.open_count = 1
do
Result := 0
across 1 |..| n as it loop
Result := Result + s.item ([it.item])
end
end
end
Elena
ELENA 6.x :
import system'routines;
import extensions;
public program()
{
var sum := new Range(1, 1000).selectBy::(x => 1.0r / (x * x)).summarize(new Real());
console.printLine(sum)
}
- Output:
1.643933566682
Elixir
iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end)
1.6439345666815615
Elm
module Main exposing (main)
import Html exposing (h1, div, p, text)
import Html.Attributes exposing (style)
aList : List Int
aList = List.range 1 1000
-- version a with a list
k2xSum : Float
k2xSum = List.sum
<| List.map (\x -> 1.0 / x / x )
<| List.map (\n -> toFloat n) aList
-- version b with a list
fx : Int -> Float
fx =
(\n -> toFloat n |> \m -> 1.0 / m / m)
f2kSum : Float
f2kSum = List.sum
<| List.map fx aList
-- version with recursion, without a list
untilMax : Int -> Int -> Float -> Float
untilMax k kmax accum =
if k > kmax
then accum
else
let
x = toFloat k
dx = 1.0 / x / x
in untilMax (k + 1) kmax (accum + dx)
recSum : Float
recSum = untilMax 1 1000 0.0
main = div [style "margin" "5%", style "color" "blue"] [
h1 [] [text "Sum of series Σ 1/k²"]
, text (" Version a with a list: Sum = " ++ String.fromFloat k2xSum)
, p [] [text (" Version b with a list: Sum = " ++ String.fromFloat f2kSum)]
, p [] [text (" Recursion version c: Sum = " ++ String.fromFloat recSum)]
]
- Output:
Sum of series Σ 1/k² Version a with a list: Sum = 1.6439345666815615 Version b with a list: Sum = 1.6439345666815615 Recursion version c: Sum = 1.6439345666815615
Emacs Lisp
(defun series (n)
(when (<= n 0)
(user-error "n must be positive"))
(apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))
(format "%.10f" (series 1000)) ;=> "1.6439345667"
Erlang
lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]).
Euphoria
This is based on the BASIC example.
function s( atom x )
return 1 / power( x, 2 )
end function
function sum( atom low, atom high )
atom ret = 0.0
for i = low to high do
ret = ret + s( i )
end for
return ret
end function
printf( 1, "%.15f\n", sum( 1, 1000 ) )
Excel
LAMBDA
Binding the names sumOfSeries, and inverseSquare to the following lambda expressions in the Name Manager of the Excel WorkBook:
(See LAMBDA: The ultimate Excel worksheet function)
Excel automatically lifts a function over a scalar to a function over an array:
sumOfSeries
=LAMBDA(f,
LAMBDA(n,
SUM(
f(SEQUENCE(n, 1, 1, 1))
)
)
)
inverseSquare
=LAMBDA(n,
1 / (n ^ 2)
)
- Output:
fx | =sumOfSeries(inverseSquare)(A2) | ||
---|---|---|---|
A | B | ||
1 | N terms | Sum of inverse square series | |
2 | 1 | 1 | |
3 | 10 | 1.5497677311665408 | |
4 | 100 | 1.63498390018489 | |
5 | 1000 | 1.64393456668156 |
Ezhil
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது
## இந்த நிரல் ஒன்று முதல் தரப்பட்ட எண் வரை 1/(எண் * எண்) எனக் கணக்கிட்டுக் கூட்டி விடை தரும்
நிரல்பாகம் தொடர்க்கூட்டல்(எண்1)
எண்2 = 0
@(எண்3 = 1, எண்3 <= எண்1, எண்3 = எண்3 + 1) ஆக
## ஒவ்வோர் எண்ணின் வர்க்கத்தைக் கணக்கிட்டு, ஒன்றை அதனால் வகுத்துக் கூட்டுகிறோம்
எண்2 = எண்2 + (1 / (எண்3 * எண்3))
முடி
பின்கொடு (எண்2)
முடி
அ = int(உள்ளீடு("ஓர் எண்ணைச் சொல்லுங்கள்: "))
பதிப்பி "நீங்கள் தந்த எண் " அ
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)
F#
The following function will do the task specified.
let rec f (x : float) =
match x with
| 0. -> x
| x -> (1. / (x * x)) + f (x - 1.)
In the interactive F# console, using the above gives:
> f 1000. ;;
val it : float = 1.643934567
However, this recursive function will run out of stack space eventually (try 100000). A tail-recursive implementation will not consume stack space and can therefore handle much larger ranges. Here is such a version:
#light
let sum_series (max : float) =
let rec f (a:float, x : float) =
match x with
| 0. -> a
| x -> f ((1. / (x * x) + a), x - 1.)
f (0., max)
[<EntryPoint>]
let main args =
let (b, max) = System.Double.TryParse(args.[0])
printfn "%A" (sum_series max)
0
This block can be compiled using fsc --target exe filename.fs or used interactively without the main function.
For a much more elegant and FP style of solving this problem, use:
Seq.sum [for x in [1..1000] do 1./(x * x |> float)]
Factor
1000 [1,b] [ >float sq recip ] map-sum
Fantom
Within 'fansh':
fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) }
1.6439345666815615
Fermat
Sigma<k=1,1000>[1/k^2]
- Output:
83545938483149689478187854264854884386044454314086472930763839512603803291207881839588904977469387999844962675327115010933 ` 903589145654299730231109091124308462732153297321867661093162618281746011828755017021645889046777854795025297006943669294 ` 330752479399654716368801794529682603741344724733173765262964463970763934463926259796895140901128384286333311745462863716 ` 753134735154188954742414035836608258393970996630553795415075904205673610359458498106833291961256452756993199997231825920 ` 203667952667546787052535763624910912251107083702817265087341966845358732584971361645348091123849687614886682117125784781 ` 422103460192439394780707024963279033532646857677925648889105430050030795563141941157379481719403833258405980463950499887 ` 302926152552848089894630843538497552630691676216896740675701385847032173192623833881016332493844186817408141003602396236 ` 858699094240207812766449 / 50820720104325812617835292273000760481839790754374852703215456050992581046448162621598030244504097 ` 240825920773913981926305208272518886258627010933716354037062979680120674828102224650586465553482032614190502746121717248 ` 161892239954030493982549422690846180552358769564169076876408783086920322038142618269982747137757706040198826719424371333 ` 781947889528085329853597116893889786983109597085041878513917342099206896166585859839289193299599163669641323895022932959 ` 750057616390808553697984192067774252834860398458100840611325353202165675189472559524948330224159123505567527375848194800 ` 452556940453530457590024173749704941834382709198515664897344438584947842793131829050180589581507273988682409028088248800 ` 576590497216884808783192565859896957125449502802395453976401743504938336291933628859306247684023233969172475385327442707 ` 968328512729836445886537101453118476390400000000; or 1.6439345666815598031390580238222155896521
Fish
0&aaa**>::*1$,&v
;n&^?:-1&+ <
Forth
: sum ( fn start count -- fsum )
0e
bounds do
i s>d d>f dup execute f+
loop drop ;
:noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt )
1 1000 sum f. \ 1.64393456668156
pi pi f* 6e f/ f. \ 1.64493406684823
Fortran
In ISO Fortran 90 and later, use SUM intrinsic:
real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /)
real :: result
result = sum(a);
Or in Fortran 77:
s=0
do i=1,1000
s=s+1./i**2
end do
write (*,*) s
end
FreeBASIC
' FB 1.05.0 Win64
Const pi As Double = 3.141592653589793
Function sumSeries (n As UInteger) As Double
If n = 0 Then Return 0
Dim sum As Double = 0
For k As Integer = 1 To n
sum += 1.0/(k * k)
Next
Return sum
End Function
Print "s(1000) = "; sumSeries(1000)
Print "zeta(2) = "; Pi * pi / 6
Print
Print "Press any key to quit"
Sleep
- Output:
s(1000) = 1.643934566681562 zeta(2) = 1.644934066848226
Frink
Frink can calculate the series with exact rational numbers or floating-point values.
sum[map[{|k| 1/k^2}, 1 to 1000]]
- Output:
83545938483149689478187854264854884386044454314086472930763839512603803291207881839588904977469387999844962675327115010933903589145654299730231109091124308462732153297321867661093162618281746011828755017021645889046777854795025297006943669294330752479399654716368801794529682603741344724733173765262964463970763934463926259796895140901128384286333311745462863716753134735154188954742414035836608258393970996630553795415075904205673610359458498106833291961256452756993199997231825920203667952667546787052535763624910912251107083702817265087341966845358732584971361645348091123849687614886682117125784781422103460192439394780707024963279033532646857677925648889105430050030795563141941157379481719403833258405980463950499887302926152552848089894630843538497552630691676216896740675701385847032173192623833881016332493844186817408141003602396236858699094240207812766449/50820720104325812617835292273000760481839790754374852703215456050992581046448162621598030244504097240825920773913981926305208272518886258627010933716354037062979680120674828102224650586465553482032614190502746121717248161892239954030493982549422690846180552358769564169076876408783086920322038142618269982747137757706040198826719424371333781947889528085329853597116893889786983109597085041878513917342099206896166585859839289193299599163669641323895022932959750057616390808553697984192067774252834860398458100840611325353202165675189472559524948330224159123505567527375848194800452556940453530457590024173749704941834382709198515664897344438584947842793131829050180589581507273988682409028088248800576590497216884808783192565859896957125449502802395453976401743504938336291933628859306247684023233969172475385327442707968328512729836445886537101453118476390400000000 (approx. 1.6439345666815598)
Change 1/k^2
to 1.0/k^2
to use floating-point math.
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
In the following function, the first parameter is the series is provided as a lambda expression. The second parameter is the number of terms to calculate
Test case
The exact value (of the sum) is:
(click to enlarge)
The approximate value is:
While the (approximate) value of π2/6 is:
GAP
# We will compute the sum exactly
# Computing an approximation of a rationnal (giving a string)
# Value is truncated toward zero
Approx := function(x, d)
local neg, a, b, n, m, s;
if x < 0 then
x := -x;
neg := true;
else
neg := false;
fi;
a := NumeratorRat(x);
b := DenominatorRat(x);
n := QuoInt(a, b);
a := RemInt(a, b);
m := 10^d;
s := "";
if neg then
Append(s, "-");
fi;
Append(s, String(n));
n := Size(s) + 1;
Append(s, String(m + QuoInt(a*m, b)));
s[n] := '.';
return s;
end;
a := Sum([1 .. 1000], n -> 1/n^2);;
Approx(a, 10);
"1.6439345666"
# and pi^2/6 is 1.6449340668, truncated to ten digits
Genie
[indent=4]
/*
Sum of series, in Genie
valac sumOfSeries.gs
./sumOfSeries
*/
delegate sumFunc(n:int):double
def sum_series(start:int, end:int, f:sumFunc):double
sum:double = 0.0
for var i = start to end do sum += f(i)
return sum
def oneOverSquare(n:int):double
return (1 / (double)(n * n))
init
Intl.setlocale()
print "ζ(2) approximation: %16.15f", sum_series(1, 1000, oneOverSquare)
print "π² / 6 : %16.15f", Math.PI * Math.PI / 6.0
- Output:
prompt$ valac sumOfSeries.gs prompt$ ./sumOfSeries ζ(2) approximation: 1.643934566681561 π² / 6 : 1.644934066848226
GEORGE
0 (s)
1, 1000 rep (i)
s 1 i dup × / + (s) ;
]
P
Output:-
1.643934566681561
Go
package main
import ("fmt"; "math")
func main() {
fmt.Println("known: ", math.Pi*math.Pi/6)
sum := 0.
for i := 1e3; i > 0; i-- {
sum += 1 / (i * i)
}
fmt.Println("computed:", sum)
}
Output:
known: 1.6449340668482264 computed: 1.6439345666815597
Groovy
Start with smallest terms first to minimize rounding error:
println ((1000..1).collect { x -> 1/(x*x) }.sum())
Output:
1.6439345654
Haskell
With a list comprehension:
sum [1 / x ^ 2 | x <- [1..1000]]
With higher-order functions:
sum $ map (\x -> 1 / x ^ 2) [1..1000]
In point-free style:
(sum . map (1/) . map (^2)) [1..1000]
or
(sum . map ((1 /) . (^ 2))) [1 .. 1000]
or, as a single fold:
seriesSum f = foldr ((+) . f) 0
inverseSquare = (1 /) . (^ 2)
main :: IO ()
main = print $ seriesSum inverseSquare [1 .. 1000]
- Output:
1.6439345666815615
Haxe
Procedural
using StringTools;
class Main {
static function main() {
var sum = 0.0;
for (x in 1...1001)
sum += 1.0/(x * x);
Sys.println('Approximation: $sum');
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}
- Output:
Approximation: 1.64393456668156146 Exact: 1.64493406684822641
Functional
using Lambda;
using StringTools;
class Main {
static function main() {
var approx = [for (x in 1...1001) x].fold(function(x, sum) return sum += 1.0 / (x * x), 0);
Sys.println('Approximation: $approx');
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}
- Output:
Same as for procedural
HicEst
REAL :: a(1000)
a = 1 / $^2
WRITE(ClipBoard, Format='F17.15') SUM(a)
1.643934566681561
Icon and Unicon
or
Note: The terse version requires some explanation. Icon expressions all return values or references if they succeed. As a result, it is possible to have expressions like these below:
IDL
print,total( 1/(1+findgen(1000))^2)
Io
Io 20110905 Io> sum := 0 ; Range 1 to(1000) foreach(k, sum = sum + 1/(k*k)) ==> 1.6439345666815615 Io> 1 to(1000) map(k, 1/(k*k)) sum ==> 1.6439345666815615 Io>
The expression using map
generates a list internally. Using foreach
does not.
J
NB. sum of reciprocals of squares of first thousand positive integers
+/ % *: >: i. 1000
1.64393
(*:o.1)%6 NB. pi squared over six, for comparison
1.64493
1r6p2 NB. As a constant (J has a rich constant notation)
1.64493
Java
public class Sum{
public static double f(double x){
return 1/(x*x);
}
public static void main(String[] args){
double start = 1;
double end = 1000;
double sum = 0;
for(double x = start;x <= end;x++) sum += f(x);
System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum);
}
}
JavaScript
ES5
function sum(a,b,fn) {
var s = 0;
for ( ; a <= b; a++) s += fn(a);
return s;
}
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156
or, in a functional idiom:
(function () {
function sum(fn, lstRange) {
return lstRange.reduce(
function (lngSum, x) {
return lngSum + fn(x);
}, 0
);
}
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
return sum(
function (x) {
return 1 / (x * x);
},
range(1, 1000)
);
})();
- Output:
1.6439345666815615
ES6
(() => {
'use strict';
// SUM OF A SERIES -------------------------------------------------------
// seriesSum :: Num a => (a -> a) -> [a] -> a
const seriesSum = (f, xs) =>
foldl((a, x) => a + f(x), 0, xs);
// GENERIC ---------------------------------------------------------------
// enumFromToInt :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// TEST ------------------------------------------------------------------
return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000));
})();
- Output:
1.6439345666815615
Joy
1000 [0] [swap -2 pow +] primrec.
- Output:
1.64393
jq
The jq idiom for efficient computation of this kind of sum is to use "reduce", either directly or using a summation wrapper function.
Directly:
def s(n): reduce range(1; n+1) as $k (0; . + 1/($k * $k) );
s(1000)
- Output:
1.6439345666815615
Using a generic summation wrapper function allows problems specified in "sigma" notation to be solved using syntax that closely resembles that notation:
def summation(s): reduce s as $k (0; . + $k);
summation( range(1; 1001) | (1/(. * .) ) )
An important point is that nothing is lost in efficiency using the declarative and quite elegant approach using "summation".
Jsish
From Javascript ES5.
#!/usr/bin/jsish
/* Sum of a series */
function sum(a:number, b:number , fn:function):number {
var s = 0;
for ( ; a <= b; a++) s += fn(a);
return s;
}
;sum(1, 1000, function(x) { return 1/(x*x); } );
/*
=!EXPECTSTART!=
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
=!EXPECTEND!=
*/
- Output:
prompt$ jsish --U sumOfSeries.jsi sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
Julia
Using a higher-order function:
julia> sum(k -> 1/k^2, 1:1000)
1.643934566681559
julia> pi^2/6
1.6449340668482264
A simple loop is more optimized:
julia> function f(n)
s = 0.0
for k = 1:n
s += 1/k^2
end
return s
end
julia> f(1000)
1.6439345666815615
K
ssr: +/1%_sqr
ssr 1+!1000
1.643935
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
val n = 1000
val sum = (1..n).sumByDouble { 1.0 / (it * it) }
println("Actual sum is $sum")
println("zeta(2) is ${Math.PI * Math.PI / 6.0}")
}
- Output:
Actual sum is 1.6439345666815615 zeta(2) is 1.6449340668482264
Lambdatalk
{+ {S.map {lambda {:k} {/ 1 {* :k :k}}} {S.serie 1 1000}}}
-> 1.6439345666815615 ~ 1.6449340668482264 = PI^2/6
Lang5
1000 iota 1 + 1 swap / 2 ** '+ reduce .
langur
writeln "calc.: ", fold fn{+}, map fn(.x) { 1/.x^2 }, 1..1000
writeln "known: ", pi^2/6
- Output:
calc.: 1.643934566681559803139058023822206 exact: 1.644934066848226436472415166646025
If we set a higher arbitrary maximum for division, we get more digits.
mode divMaxScale = 100
writeln "calc.: ", fold fn{+}, map fn(.x) 1/.x^2, 1..1000
writeln "known: ", pi^2/6
- Output:
calc.: 1.6439345666815598031390580238222155896521034464936853167172372054281147052136371544864376381235947140 exact: 1.6449340668482264364724151666460251892189499012067984377355582293700074704032008738336289006197587053
Lasso
define sum_of_a_series(n::integer,k::integer) => {
local(sum = 0)
loop(-from=#k,-to=#n) => {
#sum += 1.00/(math_pow(loop_count,2))
}
return #sum
}
sum_of_a_series(1000,1)
- Output:
1.643935
LFE
With lists:foldl
(defun sum-series (nums)
(lists:foldl
#'+/2
0
(lists:map
(lambda (x) (/ 1 x x))
nums)))
With lists:sum
(defun sum-series (nums)
(lists:sum
(lists:map
(lambda (x) (/ 1 x x))
nums)))
Both have the same result:
> (sum-series (lists:seq 1 100000))
1.6449240668982423
Liberty BASIC
for i =1 to 1000
sum =sum +1 /( i^2)
next i
print sum
end
Lingo
the floatprecision = 8
sum = 0
repeat with i = 1 to 1000
sum = sum + 1/power(i, 2)
end repeat
put sum
-- 1.64393457
LiveCode
repeat with i = 1 to 1000
add 1/(i^2) to summ
end repeat
put summ //1.643935
Logo
to series :fn :a :b
localmake "sigma 0
for [i :a :b] [make "sigma :sigma + invoke :fn :i]
output :sigma
end
to zeta.2 :x
output 1 / (:x * :x)
end
print series "zeta.2 1 1000
make "pi (radarctan 0 1) * 2
print :pi * :pi / 6
Lua
sum = 0
for i = 1, 1000 do sum = sum + 1/i^2 end
print(sum)
Lucid
series = ssum asa n >= 1000
where
num = 1 fby num + 1;
ssum = ssum + 1/(num * num)
end;
Maple
sum(1/k^2, k=1..1000);
- Output:
-Psi(1, 1001)+(1/6)*Pi^2
Mathematica/Wolfram Language
This is the straightforward solution of the task:
Sum[1/x^2, {x, 1, 1000}]
However this returns a quotient of two huge integers (namely the exact sum); to get a floating point approximation, use N:
N[Sum[1/x^2, {x, 1, 1000}]]
or better:
NSum[1/x^2, {x, 1, 1000}]
Which gives a higher or equal accuracy/precision. Alternatively, get Mathematica to do the whole calculation in floating point by using a floating point value in the formula:
Sum[1./x^2, {x, 1, 1000}]
Other ways include (exact, approximate,exact,approximate):
Total[Table[1/x^2, {x, 1, 1000}]]
Total[Table[1./x^2, {x, 1, 1000}]]
Plus@@Table[1/x^2, {x, 1, 1000}]
Plus@@Table[1./x^2, {x, 1, 1000}]
MATLAB
sum([1:1000].^(-2))
Maxima
(%i45) sum(1/x^2, x, 1, 1000);
835459384831496894781878542648[806 digits]396236858699094240207812766449
(%o45) ------------------------------------------------------------------------
508207201043258126178352922730[806 digits]886537101453118476390400000000
(%i46) sum(1/x^2, x, 1, 1000),numer;
(%o46) 1.643934566681561
MAXScript
total = 0
for i in 1 to 1000 do
(
total += 1.0 / pow i 2
)
print total
min
0 1 (
((dup * 1 swap /) (id)) cleave
((+) (succ)) spread
) 1000 times pop print
- Output:
1.643934566681562
MiniScript
zeta = function(num)
return 1 / num^2
end function
sum = function(start, finish, formula)
total = 0
for i in range(start, finish)
total = total + formula(i)
end for
return total
end function
print sum(1, 1000, @zeta)
- Output:
1.643935
МК-61/52
0 П0 П1 ИП1 1 + П1 x^2 1/x ИП0
+ П0 ИП1 1 0 0 0 - x>=0 03
ИП0 С/П
ML
Standard ML
(* 1.64393456668 *)
List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0)))
mLite
println ` fold (+, 0) ` map (fn x = 1 / x ^ 2) ` iota (1,1000);
Output:
1.6439345666815549
MMIX
x IS $1 % flt calculations
y IS $2 % id
z IS $3 % z = sum series
t IS $4 % temp var
LOC Data_Segment
GREG @
BUF OCTA 0,0,0 % print buffer
LOC #1000
GREG @
// print floating point number in scientific format: 0.xxx...ey..
// most of this routine is adopted from:
// http://www.pspu.ru/personal/eremin/emmi/rom_subs/printreal.html
// float number in z
GREG @
NaN BYTE "NaN..",0
NewLn BYTE #a,0
1H LDA x,NaN
TRAP 0,Fputs,StdOut
GO $127,$127,0
prtFlt FUN x,z,z % test if z == NaN
BNZ x,1B
CMP $73,z,0 % if necessary remember it is neg
BNN $73,4F
Sign BYTE '-'
LDA $255,Sign
TRAP 0,Fputs,StdOut
ANDNH z,#8000 % make number pos
// normalizing float number
4H SETH $74,#4024 % initialize mulfactor = 10.0
SETH $73,#0023
INCMH $73,#86f2
INCML $73,#6fc1 %
FLOT $73,$73 % $73 = float 10^16
SET $75,16 % set # decimals to 16
8H FCMP $72,z,$73 % while z >= 10^16 do
BN $72,9F %
FDIV z,z,$74 % z = z / 10.0
ADD $75,$75,1 % incr exponent
JMP 8B % wend
9H FDIV $73,$73,$74 % 10^16 / 10.0
5H FCMP $72,z,$73 % while z < 10^15 do
BNN $72,6F
FMUL z,z,$74 % z = z * 10.0
SUB $75,$75,1 % exp = exp - 1
JMP 5B
NulPnt BYTE '0','.',#00
6H LDA $255,NulPnt % print '0.' to StdOut
TRAP 0,Fputs,StdOut
FIX z,0,z % convert float z to integer
// print mantissa
0H GREG #3030303030303030
STO 0B,BUF
STO 0B,BUF+8 % store print mask in buffer
LDA $255,BUF+16 % points after LSD
% repeat
2H SUB $255,$255,1 % move pointer down
DIV z,z,10 % (q,r) = divmod z 10
GET t,rR % get remainder
INCL t,'0' % convert to ascii digit
STBU t,$255,0 % store digit in buffer
BNZ z,2B % until q == 0
TRAP 0,Fputs,StdOut % print mantissa
Exp BYTE 'e',#00
LDA $255,Exp % print 'exponent' indicator
TRAP 0,Fputs,StdOut
// print exponent
0H GREG #3030300000000000
STO 0B,BUF
LDA $255,BUF+2 % store print mask in buffer
CMP $73,$75,0 % if exp neg then place - in buffer
BNN $73,2F
ExpSign BYTE '-'
LDA $255,ExpSign
TRAP 0,Fputs,StdOut
NEG $75,$75 % make exp positive
2H LDA $255,BUF+3 % points after LSD
% repeat
3H SUB $255,$255,1 % move pointer down
DIV $75,$75,10 % (q,r) = divmod exp 10
GET t,rR
INCL t,'0'
STBU t,$255,0 % store exp. digit in buffer
BNZ $75,3B % until q == 0
TRAP 0,Fputs,StdOut % print exponent
LDA $255,NewLn
TRAP 0,Fputs,StdOut % do a NL
GO $127,$127,0 % return
i IS $5 ;iu IS $6
Main SET iu,1000
SETH y,#3ff0 y = 1.0
SETH z,#0000 z = 0.0
SET i,1 for (i=1;i<=1000; i++ ) {
1H FLOT x,i x = int i
FMUL x,x,x x = x^2
FDIV x,y,x x = 1 / x
FADD z,z,x s = s + x
ADD i,i,1
CMP t,i,iu
PBNP t,1B } z = sum
GO $127,prtFlt print sum --> StdOut
TRAP 0,Halt,0
Output:
~/MIX/MMIX/Rosetta> mmix sumseries 0.1643934566681562e1
Modula-2
MODULE SeriesSum;
FROM InOut IMPORT WriteLn;
FROM RealInOut IMPORT WriteReal;
TYPE RealFunc = PROCEDURE (REAL): REAL;
PROCEDURE seriesSum(k, n: CARDINAL; f: RealFunc): REAL;
VAR total: REAL;
i: CARDINAL;
BEGIN
total := 0.0;
FOR i := k TO n DO
total := total + f(FLOAT(i));
END;
RETURN total;
END seriesSum;
PROCEDURE oneOverKSquared(k: REAL): REAL;
BEGIN
RETURN 1.0 / (k * k);
END oneOverKSquared;
BEGIN
WriteReal(seriesSum(1, 1000, oneOverKSquared), 10);
WriteLn;
END SeriesSum.
- Output:
1.6439E+00
Modula-3
Modula-3 uses D0 after a floating point number as a literal for LONGREAL.
MODULE Sum EXPORTS Main;
IMPORT IO, Fmt, Math;
VAR sum: LONGREAL := 0.0D0;
PROCEDURE F(x: LONGREAL): LONGREAL =
BEGIN
RETURN 1.0D0 / Math.pow(x, 2.0D0);
END F;
BEGIN
FOR i := 1 TO 1000 DO
sum := sum + F(FLOAT(i, LONGREAL));
END;
IO.Put("Sum of F(x) from 1 to 1000 is ");
IO.Put(Fmt.LongReal(sum));
IO.Put("\n");
END Sum.
Output:
Sum of F(x) from 1 to 1000 is 1.6439345666815612
MUMPS
SOAS(N)
NEW SUM,I SET SUM=0
FOR I=1:1:N DO
.SET SUM=SUM+(1/((I*I)))
QUIT SUM
This is an extrinsic function so the usage is:
USER>SET X=$$SOAS^ROSETTA(1000) WRITE X 1.643934566681559806
NewLISP
(let (s 0)
(for (i 1 1000)
(inc s (div 1 (* i i))))
(println s))
Nial
|sum (1 / power (count 1000) 2)
=1.64393
Nim
var s = 0.0
for n in 1..1000: s += 1 / (n * n)
echo s
- Output:
1.643934566681561
Oberon-2
MODULE SS;
IMPORT Out;
TYPE
RealFunc = PROCEDURE(r:REAL):REAL;
PROCEDURE SeriesSum(k,n:LONGINT;f:RealFunc):REAL;
VAR
total:REAL;
i:LONGINT;
BEGIN
total := 0.0;
FOR i := k TO n DO total := total + f(i) END;
RETURN total
END SeriesSum;
PROCEDURE OneOverKSquared(k:REAL):REAL;
BEGIN RETURN 1.0 / (k * k)
END OneOverKSquared;
BEGIN
Out.Real(SeriesSum(1,1000,OneOverKSquared),10);
Out.Ln;
END SS.
- Output:
1.64393E+00
Objeck
bundle Default {
class SumSeries {
function : Main(args : String[]) ~ Nil {
DoSumSeries();
}
function : native : DoSumSeries() ~ Nil {
start := 1;
end := 1000;
sum := 0.0;
for(x : Float := start; x <= end; x += 1;) {
sum += f(x);
};
IO.Console->GetInstance()->Print("Sum of f(x) from ")->Print(start)->Print(" to ")->Print(end)->Print(" is ")->PrintLine(sum);
}
function : native : f(x : Float) ~ Float {
return 1.0 / (x * x);
}
}
}
OCaml
let sum a b fn =
let result = ref 0. in
for i = a to b do
result := !result +. fn i
done;
!result
# sum 1 1000 (fun x -> 1. /. (float x ** 2.)) - : float = 1.64393456668156124
or in a functional programming style:
let sum a b fn =
let rec aux i r =
if i > b then r
else aux (succ i) (r +. fn i)
in
aux a 0.
;;
Simple recursive solution:
let rec sum n = if n < 1 then 0.0 else sum (n-1) +. 1.0 /. float (n*n)
in sum 1000
Octave
Given a vector, the sum of all its elements is simply sum(vector)
; a range can be generated through the range notation: sum(1:1000)
computes the sum of all numbers from 1 to 1000. To compute the requested series, we can simply write:
sum(1 ./ [1:1000] .^ 2)
Oforth
: sumSerie(s, n) 0 n seq apply(#[ s perform + ]) ;
Usage :
#[ sq inv ] 1000 sumSerie println
- Output:
1.64393456668156
OpenEdge/Progress
Conventionally like elsewhere:
def var dcResult as decimal no-undo.
def var n as int no-undo.
do n = 1 to 1000 :
dcResult = dcResult + 1 / (n * n) .
end.
display dcResult .
or like this:
def var n as int no-undo.
repeat n = 1 to 1000 :
accumulate 1 / (n * n) (total).
end.
display ( accum total 1 / (n * n) ) .
Oz
With higher-order functions:
declare
fun {SumSeries S N}
{FoldL {Map {List.number 1 N 1} S}
Number.'+' 0.}
end
fun {S X}
1. / {Int.toFloat X*X}
end
in
{Show {SumSeries S 1000}}
Iterative:
fun {SumSeries S N}
R = {NewCell 0.}
in
for I in 1..N do
R := @R + {S I}
end
@R
end
Panda
sum{{1.0.divide(1..1000.sqr)}}
Output:
1.6439345666815615
PARI/GP
Exact rational solution:
sum(n=1,1000,1/n^2)
Real number solution (accurate to at standard precision):
sum(n=1,1000,1./n^2)
Approximate solution (accurate to at standard precision):
zeta(2)-intnum(x=1000.5,[1],1/x^2)
or
zeta(2)-1/1000.5
Pascal
Program SumSeries;
type
tOutput = double;//extended;
tmyFunc = function(number: LongInt): tOutput;
function f(number: LongInt): tOutput;
begin
f := 1/sqr(tOutput(number));
end;
function Sum(from,upto: LongInt;func:tmyFunc):tOutput;
var
res: tOutput;
begin
res := 0.0;
// for from:= from to upto do res := res + f(from);
for upTo := upto downto from do res := res + f(upTo);
Sum := res;
end;
BEGIN
writeln('The sum of 1/x^2 from 1 to 1000 is: ', Sum(1,1000,@f));
writeln('Whereas pi^2/6 is: ', pi*pi/6:10:8);
end.
Output
different version of type and calculation extended low to high 1.64393456668155980263E+0000 extended high to low 1.64393456668155980307E+0000 double low to high 1.6439345666815612E+000 double high to low 1.6439345666815597E+000 Out: The sum of 1/x^2 from 1 to 1000 is: 1.6439345666815612E+000 Whereas pi^2/6 is: 1.64493407
Perl
my $sum = 0;
$sum += 1 / $_ ** 2 foreach 1..1000;
print "$sum\n";
or
use List::Util qw(reduce);
$sum = reduce { $a + 1 / $b ** 2 } 0, 1..1000;
print "$sum\n";
An other way of doing it is to define the series as a closure:
my $S = do { my ($sum, $k); sub { $sum += 1/++$k**2 } };
my @S = map &$S, 1 .. 1000;
print $S[-1];
Phix
function sumto(atom n) atom res = 0 for i=1 to n do res += 1/(i*i) end for return res end function ?sumto(1000)
- Output:
1.643934567
PHP
<?php
/**
* @author Elad Yosifon
*/
/**
* @param int $n
* @param int $k
* @return float|int
*/
function sum_of_a_series($n,$k)
{
$sum_of_a_series = 0;
for($i=$k;$i<=$n;$i++)
{
$sum_of_a_series += (1/($i*$i));
}
return $sum_of_a_series;
}
echo sum_of_a_series(1000,1);
- Output:
1.6439345666816
Picat
List comprehension
s(N) = sum([1.0/K**2 : K in 1..N]).
Iterative
s2(N) = Sum =>
K = 1,
Sum1 = 0,
while(K <= N)
Sum1 := Sum1 + 1/K**2,
K := K + 1
end,
Sum = Sum1.
Test
go =>
% List comprehension
test(s,1000),
nl,
% Iterative
test(s2,1000),
nl.
test(Fun,N) =>
println([fun=Fun,n=N]),
Pi2_6 = math.pi**2/6,
println(Pi2_6='math.pi**2/6'),
nl,
foreach(I in 1..6)
S = apply(Fun,10**I),
printf("%f (diff: %w)\n", S,Pi2_6-S)
end,
nl.
- Output:
[fun = s,n = 1000] 1.644934066848226 = math.pi**2/6 1.549768 (diff: 0.095166335681686) 1.634984 (diff: 0.009950166663334) 1.643935 (diff: 0.000999500166665) 1.644834 (diff: 0.000099995000161) 1.644924 (diff: 0.000009999949984) 1.644933 (diff: 0.000000999999456) [fun = s2,n = 1000] 1.644934066848226 = math.pi**2/6 1.549768 (diff: 0.095166335681686) 1.634984 (diff: 0.009950166663334) 1.643935 (diff: 0.000999500166665) 1.644834 (diff: 0.000099995000161) 1.644924 (diff: 0.000009999949984) 1.644933 (diff: 0.000000999999456)
PicoLisp
(scl 9) # Calculate with 9 digits precision
(let S 0
(for I 1000
(inc 'S (*/ 1.0 (* I I))) )
(prinl (round S 6)) ) # Round result to 6 digits
Output:
1.643935
Pike
array(int) x = enumerate(1000,1,1);
`+(@(1.0/pow(x[*],2)[*]));
Result: 1.64393
PL/I
/* sum the first 1000 terms of the series 1/n**2. */
s = 0;
do i = 1000 to 1 by -1;
s = s + 1/float(i**2);
end;
put skip list (s);
- Output:
1.64393456668155980E+0000
Pop11
lvars s = 0, j;
for j from 1 to 1000 do
s + 1.0/(j*j) -> s;
endfor;
s =>
PostScript
/aproxriemann{
/x exch def
/i 1 def
/sum 0 def
x{
/sum sum i -2 exp add def
/i i 1 add def
}repeat
sum ==
}def
1000 aproxriemann
Output:
1.64393485
% using map
[1 1000] 1 range {dup * 1 exch div} map 0 {+} fold
% just using fold
[1 1000] 1 range 0 {dup * 1 exch div +} fold
Potion
sum = 0.0
1 to 1000 (i): sum = sum + 1.0 / (i * i).
sum print
PowerShell
$x = 1..1000 `
| ForEach-Object { 1 / ($_ * $_) } `
| Measure-Object -Sum
Write-Host Sum = $x.Sum
Prolog
Works with SWI-Prolog.
sum(S) :-
findall(L, (between(1,1000,N),L is 1/N^2), Ls),
sumlist(Ls, S).
Ouptput :
?- sum(S). S = 1.643934566681562.
PureBasic
Define i, sum.d
For i=1 To 1000
sum+1.0/(i*i)
Next i
Debug sum
Answer = 1.6439345666815615
Python
print ( sum(1.0 / (x * x) for x in range(1, 1001)) )
Or, as a generalised map, or fold / reduction – (see Catamorphism#Python):
'''The sum of a series'''
from functools import reduce
# seriesSumA :: (a -> b) -> [a] -> b
def seriesSumA(f):
'''The sum of the map of f over xs.'''
return lambda xs: sum(map(f, xs))
# seriesSumB :: (a -> b) -> [a] -> b
def seriesSumB(f):
'''Folding acc + f(x) over xs where acc begins at 0.'''
return lambda xs: reduce(
lambda a, x: a + f(x), xs, 0
)
# TEST ----------------------------------------------------
# main:: IO ()
def main():
'''Summing 1/x^2 over x = 1..1000'''
def f(x):
return 1 / (x * x)
print(
fTable(
__doc__ + ':\n' + '(1/x^2 over x = 1..1000)'
)(lambda f: '\tby ' + f.__name__)(str)(
lambda g: g(f)(enumFromTo(1)(1000))
)([seriesSumA, seriesSumB])
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# fTable :: String -> (a -> String) ->
# (b -> String) ->
# (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(xShow), xs))
return s + '\n' + '\n'.join([
xShow(x).rjust(w, ' ') + (
' -> '
) + fxShow(f(x)) for x in xs
])
return lambda xShow: lambda fxShow: (
lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
The sum of a series: (1/x^2 over x = 1..1000) by seriesSumA -> 1.6439345666815615 by seriesSumB -> 1.6439345666815615
Q
sn:{sum xexp[;-2] 1+til x}
sn 1000
- Output:
1.643935
Quackery
Using the Quackery bignum rational arithmetic suite bigrat.qky
.
[ $ "bigrat.qky" loadfile ] now!
[ 0 n->v rot times
[ i^ 1+ 2 ** n->v 1/v v+ ] ] is sots ( n --> n/d )
1000 sots
2dup
proper 1000000 round improper
say "Sum of the series to n=1000."
cr cr
say "As a proper fraction, best approximation where the denominator does not exceed 1 million."
cr cr
proper$ echo$ say " (Correct to ten places after the decimal point.)"
cr cr
say "As a decimal fraction, first 1000 places after the decimal point."
cr cr
1000 point$ echo$
- Output:
Sum of the series to n=1000. As a proper fraction, best approximation where the denominator does not exceed 1 million. 1 120258/186755 (Correct to ten places after the decimal point.) As a decimal fraction, first 1000 places after the decimal point. 1.6439345666815598031390580238222155896521034464936853167172372054281147052136371544864376381235947140840247689830052307986940209330560586814364561437341082161835849587934021025978122814760355990612544129425222414004531893441493046096060608253065583656711834617047405403932309749347134167799683552617330444813936406879861764067575322580319473862296485681925322084905899406792924876019403018468725753572490400061711335030331913299036845451416705045304303525919036749150124063804931627056349457943068021121600349225249063311667960633996823281725263770542297902063202752003109461373037518723003263479387388393217302120377472207068721127250339809048861023369090772476245864265860225860011245643262424159227627089164279360808513966752516418684047190163638741163457263381145491031118582607024223083056005537196735365330300185181967964028738217100545990163108755787441026888189509196651819302024386462242896954169347538400396493562377033255763634275476803474905179930119321187665211349199562778792639603861646
R
print( sum( 1/seq(1000)^2 ) )
Racket
A solution using Typed Racket:
#lang typed/racket
(: S : Natural -> Real)
(define (S n)
(for/sum: : Real ([k : Natural (in-range 1 (+ n 1))])
(/ 1.0 (* k k))))
Raku
(formerly Perl 6)
In general, the $n
th partial sum of a series whose terms are given by a unary function &f
is
[+] map &f, 1 .. $n
So what's needed in this case is
say [+] map { 1 / $^n**2 }, 1 .. 1000;
Or, using the "hyper" metaoperator to vectorize, we can use a more "point free" style while keeping traditional precedence:
say [+] 1 «/« (1..1000) »**» 2;
Or we can use the X "cross" metaoperator, which is convenient even if one side or the other is a scalar. In this case, we demonstrate a scalar on either side:
say [+] 1 X/ (1..1000 X** 2);
Note that cross ops are parsed as list infix precedence rather than using the precedence of the base op as hypers do. Hence the difference in parenthesization.
With list comprehensions, you can write:
say [+] (1 / $_**2 for 1..1000);
That's fine for a single result, but if you're going to be evaluating the sequence multiple times, you don't want to be recalculating the sum each time, so it's more efficient to define the sequence as a constant to let the run-time automatically cache those values already calculated. In a lazy language like Raku, it's generally considered a stronger abstraction to write the correct infinite sequence, and then take the part of it you're interested in. Here we define an infinite sequence of partial sums (by adding a backslash into the reduction to make it look "triangular"), then take the 1000th term of that:
constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *;
say @x[1000]; # prints 1.64393456668156
Note that infinite constant sequences can be lazily generated in Raku, or this wouldn't work so well...
A cleaner style is to combine these approaches with a more FP look:
constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*;
say ζish[1000];
Perhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization:
use experimental :cached;
sub ζ($s) is cached { [\+] 1..* X** -$s }
say ζ(2)[1000];
Notice how the thus-defined zeta function returns a lazy list of approximated values, which is arguably the closest we can get from the mathematical definition.
Raven
0 1 1000 1 range each 1.0 swap dup * / +
"%g\n" print
- Output:
1.64393
Raven uses a 32 bit float, so precision limits the accuracy of the result for large iterations.
Red
Red []
s: 0
repeat n 1000 [ s: 1.0 / n ** 2 + s ]
print s
REXX
sums specific terms
/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */
parse arg N D . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
if D=='' | D=="," then D= 60 /* " " " " " " */
numeric digits D /*use D digits (9 is the REXX default).*/
$=0 /*initialize the sum to zero. */
do k=1 for N /* [↓] compute for N terms. */
$=$ + 1/k**2 /*add a squared reciprocal to the sum. */
end /*k*/
say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */
output when using the default input:
The sum of 1000 terms is: 1.64393456668155980313905802382221558965210344649368531671713
sums with running total
This REXX version shows the running total for every 10th term.
/*REXX program sums the first N terms o f 1/(k**2), k=1 ──► N. */
parse arg N D . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
if D=='' | D=="," then D= 60 /* " " " " " " */
numeric digits D /*use D digits (9 is the REXX default).*/
w=length(N) /*W is used for aligning the output. */
$=0 /*initialize the sum to zero. */
do k=1 for N /* [↓] compute for N terms. */
$=$ + 1/k**2 /*add a squared reciprocal to the sum. */
parse var k s 2 m '' -1 e /*obtain the start and end decimal digs*/
if e\==0 then iterate /*does K end with the dec digit 0 ? */
if s\==1 then iterate /* " " start " " " " 1 ? */
if m\=0 then iterate /* " " middle contain any non-zero ?*/
if k==N then iterate /* " " equal N, then skip running sum*/
say 'The sum of' right(k,w) "terms is:" $ /*display a running sum.*/
end /*k*/
say /*a blank line for sep. */
say 'The sum of' right(k-1,w) "terms is:" $ /*display the final sum.*/
/*stick a fork in it, we're all done. */
output when using the input of: 1000000000
The sum of 10 terms is: 1.54976773116654069035021415973796926177878558830939783320736 The sum of 100 terms is: 1.63498390018489286507716949818032376668332170003126381385307 The sum of 1000 terms is: 1.64393456668155980313905802382221558965210344649368531671713 The sum of 10000 terms is: 1.64483407184805976980608183331031090353799751949684175308996 The sum of 100000 terms is: 1.64492406689822626980574850331269185564752132981156034248806 The sum of 1000000 terms is: 1.64493306684872643630574849997939185588561654406394129491321 The sum of 10000000 terms is: 1.64493396684823143647224849997935852288561656787346272343397 The sum of 100000000 terms is: 1.64493405684822648647241499997935852255228656787346510441026 The sum of 1000000000 terms is: 1.64493406584822643697241516647935852255228323457346510444171
output from a calculator computing 2/6, (using 60 digits) showing the correct number (nine) of decimal digits [the superscripting of the digits was edited after-the-fact]:
1.64493406684822643647241516664602518921894990120679843773556
sums with running significance
This is a technique to show a running significance (based on the previous calculation).
If the old REXX variable would be set to 1.64 (instead of 1), the first noise digits could be bypassed to make the display cleaner.
/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */
parse arg N D . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
if D=='' | D=="," then D= 60 /* " " " " " " */
numeric digits D /*use D digits (9 is the REXX default).*/
w=length(N) /*W is used for aligning the output. */
$=0 /*initialize the sum to zero. */
old=1 /*the new sum to compared to the old. */
p=0 /*significant decimal precision so far.*/
do k=1 for N /* [↓] compute for N terms. */
$=$ + 1/k**2 /*add a squared reciprocal to the sum. */
c=compare($,old) /*see how we're doing with precision. */
if c>p then do /*Got another significant decimal dig? */
say 'The significant sum of' right(k,w) "terms is:" left($,c)
p=c /*use the new significant precision. */
end /* [↑] display significant part of sum*/
old=$ /*use "old" sum for the next compare. */
end /*k*/
say /*display blank line for the separator.*/
say 'The sum of' right(N,w) "terms is:" /*display the sum's preamble line. */
say $ /*stick a fork in it, we're all done. */
output when using the input of (one billion [limit], and one hundred decimal digits): 1000000000 100
The significant sum of 3 terms is: 1.3 The significant sum of 5 terms is: 1.46 The significant sum of 14 terms is: 1.575 The significant sum of 34 terms is: 1.6159 The significant sum of 110 terms is: 1.63588 The significant sum of 328 terms is: 1.641889 The significant sum of 1024 terms is: 1.6439579 The significant sum of 3207 terms is: 1.64462229 The significant sum of 10043 terms is: 1.644834499 The significant sum of 31782 terms is: 1.6449026029 The significant sum of 100314 terms is: 1.64492409819 The significant sum of 316728 terms is: 1.644930909569 The significant sum of 1000853 terms is: 1.6449330677009 The significant sum of 3163463 terms is: 1.64493375073899 The significant sum of 10001199 terms is: 1.644933966860219 The significant sum of 31627592 terms is: 1.6449340352302649 The significant sum of 100009299 terms is: 1.64493405684915629 The significant sum of 316233759 terms is: 1.644934063686008709 The sum of 1000000000 terms is: 1.644934065848226436972415166479358522552283234573465104402224896012864613260343731009819376810240620
One can see a pattern in the number of significant digits computed based on the number of terms used. (See a discussion in the talk section.)
Ring
sum = 0
for i =1 to 1000
sum = sum + 1 /(pow(i,2))
next
decimals(8)
see sum
RLaB
>> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6
-0.000999500167
RPL
≪ 0 1 ROT FOR k SQ INV + NEXT ≫ '∑INV2' STO
1000 ∑INV2
The emulator immediately returns
1: 1.64393456668
A basic HP-28S calculator returns after 27.5 seconds
1: 1.64393456674
'k' 1 1000 '1/SQ(k)' ∑
returns in 2 minutes 27 seconds, with exact mode set:
1: 83545938483149689478187854264854884386044454314086472930763839512603803291207881839588904977469387999844962675327115010933903589145654299730231109091124308462732153297321867661093162618281746011828755017021645889046777854795025297006943669294330752479399654716368801794529682603741344724733173765262964463970763934463926259796895140901128384286333311745462863716753134735154188954742414035836608258393970996630553795415075904205673610359458498106833291961256452756993199997231825920203667952667546787052535763624910912251107083702817265087341966845358732584971361645348091123849687614886682117125784781422103460192439394780707024963279033532646857677925648889105430050030795563141941157379481719403833258405980463950499887302926152552848089894630843538497552630691676216896740675701385847032173192623833881016332493844186817408141003602396236858699094240207812766449 / 50820720104325812617835292273000760481839790754374852703215456050992581046448162621598030244504097240825920773913981926305208272518886258627010933716354037062979680120674828102224650586465553482032614190502746121717248161892239954030493982549422690846180552358769564169076876408783086920322038142618269982747137757706040198826719424371333781947889528085329853597116893889786983109597085041878513917342099206896166585859839289193299599163669641323895022932959750057616390808553697984192067774252834860398458100840611325353202165675189472559524948330224159123505567527375848194800452556940453530457590024173749704941834382709198515664897344438584947842793131829050180589581507273988682409028088248800576590497216884808783192565859896957125449502802395453976401743504938336291933628859306247684023233969172475385327442707968328512729836445886537101453118476390400000000
Ruby
puts (1..1000).sum{ |x| 1r / x ** 2 }.to_f
- Output:
1.64393456668156
Run BASIC
for i =1 to 1000
sum = sum + 1 /( i^2)
next i
print sum
Rust
const LOWER: i32 = 1;
const UPPER: i32 = 1000;
// Because the rule for our series is simply adding one, the number of terms are the number of
// digits between LOWER and UPPER
const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER;
fn main() {
// Formulaic method
println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) / 2);
// Naive method
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}
SAS
data _null_;
s=0;
do n=1 to 1000;
s+1/n**2; /* s+x is synonym of s=s+x */
end;
e=s-constant('pi')**2/6;
put s e;
run;
Scala
scala> 1 to 1000 map (x => 1.0 / (x * x)) sum
res30: Double = 1.6439345666815615
Scheme
(define (sum a b fn)
(do ((i a (+ i 1))
(result 0 (+ result (fn i))))
((> i b) result)))
(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction
(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal
More idiomatic way (or so they say) by tail recursion:
(define (invsq f to)
(let loop ((f f) (s 0))
(if (> f to)
s
(loop (+ 1 f) (+ s (/ 1 f f))))))
;; whether you get a rational or a float depends on implementation
(invsq 1 1000) ; 835459384831...766449/50820...90400000000
(exact->inexact (invsq 1 1000)) ; 1.64393456668156
Seed7
$ include "seed7_05.s7i";
include "float.s7i";
const func float: invsqr (in float: n) is
return 1.0 / n**2;
const proc: main is func
local
var integer: i is 0;
var float: sum is 0.0;
begin
for i range 1 to 1000 do
sum +:= invsqr(flt(i));
end for;
writeln(sum digits 6 lpad 8);
end func;
SETL
print( +/[1/k**2 : k in [1..1000]] );
- Output:
1.64393456668156
Sidef
say sum(1..1000, {|n| 1 / n**2 })
Alternatively, using the reduce{} method:
say (1..1000 -> reduce { |a,b| a + (1 / b**2) })
- Output:
1.64393456668155980313905802382221558965210344649369
Slate
Manually coerce it to a float, otherwise you will get an exact (and slow) answer:
((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).
Smalltalk
( (1 to: 1000) fold: [:sum :aNumber |
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "sumseries" )
@( description, "Compute the nth term of a series, i.e. the " )
@( description, "sum of the n first terms of the " )
@( description, "corresponding sequence. For this task " )
@( description, "repeat 1000 times. " )
@( see_also, "http://rosettacode.org/wiki/Sum_of_a_series" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure sumseries is
function inverse_square( x : long_float ) return long_float is
begin
return 1/x**2;
end inverse_square;
total : long_float := 0.0;
max_param : constant natural := 1000;
begin
for i in 1..max_param loop
total := @ + inverse_square( i );
end loop;
put( "Sum of F(x) from 1 to" )
@( max_param )
@( " is" )
@( total );
new_line;
end sumseries;
SQL
create table t1 (n real);
-- this is postgresql specific, fill the table
insert into t1 (select generate_series(1,1000)::real);
with tt as (
select 1/(n*n) as recip from t1
) select sum(recip) from tt;
Result of select (with locale DE):
sum ------------------ 1.64393456668156 (1 Zeile)
Stata
function series(n) {
return(sum((n..1):^-2))
}
series(1000)-pi()^2/6
-.0009995002
Swift
func sumSeries(var n: Int) -> Double {
var ret: Double = 0
for i in 1...n {
ret += (1 / pow(Double(i), 2))
}
return ret
}
output: 1.64393456668156
Swift also allows extension to datatypes. Here's similar code using an extension to Int.
extension Int {
func SumSeries() -> Double {
var ret: Double = 0
for i in 1...self {
ret += (1 / pow(Double(i), 2))
}
return ret
}
}
var x: Int = 1000
var y: Double
y = x.sumSeries() /* y = 1.64393456668156 */
Swift also allows you to do this:
y = 1000.sumSeries()
Tcl
Using Expansion Operator and mathop
package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::} ;# Ease of access to mathop commands
proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} ;# an expr would be clearer, but this is a demonstration of mathop
# using range function defined below
lsum_series [range 1 1001] ;# ==> 1.6439345666815615
Using Loop
package require Tcl 8.5
proc partial_sum {func - start - stop} {
for {set x $start; set sum 0} {$x <= $stop} {incr x} {
set sum [expr {$sum + [apply $func $x]}]
}
return $sum
}
set S {x {expr {1.0 / $x**2}}}
partial_sum $S from 1 to 1000 ;# => 1.6439345666815615
Using tcllib
package require Tcl 8.5
package require struct::list
proc sum_of {lambda nums} {
struct::list fold [struct::list map $nums [list apply $lambda]] 0 ::tcl::mathop::+
}
set S {x {expr {1.0 / $x**2}}}
sum_of $S [range 1 1001] ;# ==> 1.6439345666815615
The helper range
procedure is:
# a range command akin to Python's
proc range args {
foreach {start stop step} [switch -exact -- [llength $args] {
1 {concat 0 $args 1}
2 {concat $args 1}
3 {concat $args }
default {error {wrong # of args: should be "range ?start? stop ?step?"}}
}] break
if {$step == 0} {error "cannot create a range when step == 0"}
set range [list]
while {$step > 0 ? $start < $stop : $stop < $start} {
lappend range $start
incr start $step
}
return $range
}
TI-83 BASIC
TI-84 Version
∑(1/X²,X,1,1000)
- Output:
1.643934567
TI-83 Version
The TI-83 does not have the new summation notation, and caps lists at 999 entries.
sum(seq(1/X²,X,1,999))
- Output:
1.643933567
TI-89 BASIC
∑(1/x^2,x,1,1000)
TXR
Reduce with + operator over a lazily generated list.
Variant A1: limit the list generation inside the gen
operator.
txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]'
1.64393456668156
Variant A2: generate infinite list, but take only the first 1000 items using [list-expr 0..999]
.
txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]'
1.64393456668156
Variant B: generate lazy integer range, and pump it through a series of function with the help of the chain
functional combinator and the op
partial evaluation/binding operator.
txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]'
1.64393456668156
Variant C: unravel the chain in Variant B using straightforward nesting.
txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]'
1.64393456668156
Variant D: bring Variant B's inverse square calculation into the fold, eliminating mapcar. Final answer.
txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]'
1.64393456668156
Unicon
See Icon.
UnixPipes
term() {
b=$1;res=$2
echo "scale=5;1/($res*$res)+$b" | bc
}
sum() {
(read B; res=$1;
test -n "$B" && (term $B $res) || (term 0 $res))
}
fold() {
func=$1
(while read a ; do
fold $func | $func $a
done)
}
(echo 3; echo 1; echo 4) | fold sum
Ursala
The expression plus:-0. represents a function returning the sum of any given list of floating point numbers, or zero if it's empty, using the built in reduction operator, :-, and the binary addition function, plus. The rest the expression constructs the series by inverting the square of each number in the list from 1 to 1000.
#import flo
#import nat
#cast %e
total = plus:-0 div/*1. sqr* float*t iota 1001
output:
1.643935e+00
Vala
public static void main(){
int i, start = 1, end = 1000;
double sum = 0.0;
for(i = start; i<= end; i++)
sum += (1 / (double)(i * i));
stdout.printf("%s\n", sum.to_string());
}
Output:
1.6439345666815615
VBA
Private Function sumto(n As Integer) As Double
Dim res As Double
For i = 1 To n
res = res + 1 / i ^ 2
Next i
sumto = res
End Function
Public Sub main()
Debug.Print sumto(1000)
End Sub
- Output:
1,64393456668156
VBScript
' Sum of a series
for i=1 to 1000
s=s+1/i^2
next
wscript.echo s
- Output:
1.64393456668156
Visual Basic .NET
' Sum of a series
Sub SumOfaSeries()
Dim s As Double
s = 0
For i = 1 To 1000
s = s + 1 / i ^ 2
Next 'i
Console.WriteLine(s)
End Sub
- Output:
1.64393456668156
Verilog
module main;
integer i;
real sum;
initial begin
sum = 0.0;
for(i = 1; i <= 1000; i=i+1) sum = sum + 1.0 / (i * i);
$display(sum);
end
endmodule
1.64393
V (Vlang)
import math
fn main(){
println('known: ${math.pi*math.pi/6}')
mut sum := f64(0)
for i :=1e3; i >0; i-- {
sum += 1/(i*i)
}
println('computed: $sum')
}
Output:
known: 1.6449340668482264 computed: 1.6439345666815597
WDTE
let s => import 'stream';
s.range 1 1001
-> s.map (@ inner k => / 1 (* k k))
-> s.reduce 0 +
-- io.writeln io.stdout
;
- Output:
1.643933567
Wortel
@sum !*#~V1Sn @to 1000 ; returns 1.6439345666815615
@to 1000 ; generates a list of 1 to 1000 (inclusive)
#~V1Sn ; number expression which stands for: square push(1) swap divide
!* ; maps the number expression over the list
@sum ; sums the list
Wren
var sumSeries = Fn.new { |n| (1..n).reduce(0) { |sum, i| sum + 1/(i*i) } }
System.print("s(1000) = %(sumSeries.call(1000))")
System.print("zeta(2) = %(Num.pi*Num.pi/6)")
- Output:
s(1000) = 1.6439345666816 zeta(2) = 1.6449340668482
XPL0
code CrLf=9; code real RlOut=48;
int X; real S;
[S:= 0.0;
for X:= 1 to 1000 do S:= S + 1.0/float(X*X);
RlOut(0, S); CrLf(0);
]
Output:
1.64393
Yorick
(1./indgen(1:1000)^2)(sum)
Zig
const std = @import("std");
fn f(x: u64) f64 {
return 1 / @as(f64, @floatFromInt(x * x));
}
fn sum(comptime func: fn (u64) f64, n: u64) f64 {
var s: f64 = 0.0;
var i: u64 = n;
while (i != 0) : (i -= 1)
s += func(i);
return s;
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("S_1000 = {d:.15}\n", .{sum(f, 1000)});
}
- Output:
S_1000 = 1.643934566681560
zkl
[1.0..1000].reduce(fcn(p,n){ p + 1.0/(n*n) },0.0) //-->1.64394
ZX Spectrum Basic
10 LET n=1000
20 LET s=0
30 FOR k=1 TO n
40 LET s=s+1/(k*k)
50 NEXT k
60 PRINT s
- Output:
1.6439346 0 OK, 60:1
- Programming Tasks
- Arithmetic operations
- 11l
- 360 Assembly
- ACL2
- Action!
- Action! Tool Kit
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- APL
- AppleScript
- Arturo
- Asymptote
- AutoHotkey
- AWK
- BASIC
- BASIC256
- BBC BASIC
- Gambas
- QBasic
- True BASIC
- XBasic
- Yabasic
- Bc
- Beads
- Befunge
- BQN
- Bracmat
- Brat
- C
- C sharp
- C++
- CLIPS
- Clojure
- CLU
- COBOL
- CoffeeScript
- Common Lisp
- Crystal
- D
- Dc
- Dart
- Delphi
- DWScript
- Dyalect
- E
- EasyLang
- EchoLisp
- EDSAC order code
- Eiffel
- Elena
- Elixir
- Elm
- Emacs Lisp
- Erlang
- Euphoria
- Excel
- Ezhil
- F Sharp
- Factor
- Fantom
- Fermat
- Fish
- Forth
- Fortran
- FreeBASIC
- Frink
- Fōrmulæ
- GAP
- Genie
- GEORGE
- Go
- Groovy
- Haskell
- Haxe
- HicEst
- Icon
- Unicon
- IDL
- Io
- J
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- K
- Kotlin
- Lambdatalk
- Lang5
- Langur
- Lasso
- LFE
- Liberty BASIC
- Lingo
- LiveCode
- Logo
- Lua
- Lucid
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- Min
- MiniScript
- МК-61/52
- ML
- Standard ML
- MLite
- MMIX
- Modula-2
- Modula-3
- MUMPS
- NewLISP
- Nial
- Nim
- Oberon-2
- Objeck
- OCaml
- Octave
- Oforth
- OpenEdge/Progress
- Oz
- Panda
- PARI/GP
- Pascal
- Perl
- Phix
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- Pop11
- PostScript
- Initlib
- Potion
- PowerShell
- Prolog
- PureBasic
- Python
- Q
- Quackery
- R
- Racket
- Raku
- Raven
- Red
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Run BASIC
- Rust
- SAS
- Scala
- Scheme
- Seed7
- SETL
- Sidef
- Slate
- Smalltalk
- SparForte
- SQL
- Stata
- Swift
- Tcl
- Tcllib
- TI-83 BASIC
- TI-89 BASIC
- TXR
- UnixPipes
- Ursala
- Vala
- VBA
- VBScript
- Visual Basic .NET
- Verilog
- V (Vlang)
- WDTE
- Wortel
- Wren
- XPL0
- Yorick
- Zig
- Zkl
- ZX Spectrum Basic
- Pages with too many expensive parser function calls