Sum of a series: Difference between revisions

Content added Content deleted
(→‎{{header|Picat}}: Split into subsections)
m (syntax highlighting fixup automation)
Line 21: Line 21:
{{trans|Python}}
{{trans|Python}}


<lang 11l>print(sum((1..1000).map(x -> 1.0/x^2)))</lang>
<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}}==
<lang 360asm>* Sum of a series 30/03/2017
<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</lang>
END SUMSER</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 59: Line 59:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang lisp>(defun sum-x^-2 (max-x)
<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)))))</lang>
(sum-x^-2 (1- max-x)))))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


PROC Calc(CARD n REAL POINTER res)
PROC Calc(CARD n REAL POINTER res)
Line 102: Line 102:
PrintF("s(%U)=",n)
PrintF("s(%U)=",n)
PrintRE(res)
PrintRE(res)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_a_series.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_a_series.png Screenshot from Atari 8-bit computer]
Line 110: Line 110:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>function partialSum(n:uint):Number
<syntaxhighlight lang="actionscript">function partialSum(n:uint):Number
{
{
var sum:Number = 0;
var sum:Number = 0;
Line 117: Line 117:
return sum;
return sum;
}
}
trace(partialSum(1000));</lang>
trace(partialSum(1000));</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;


procedure Sum_Series is
procedure Sum_Series is
Line 139: Line 139:
Put(Item => Sum, Aft => 10, Exp => 0);
Put(Item => Sum, Aft => 10, Exp => 0);
New_Line;
New_Line;
end Sum_Series;</lang>
end Sum_Series;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>real
<syntaxhighlight lang="aime">real
Invsqr(real n)
Invsqr(real n)
{
{
Line 166: Line 166:


0;
0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>MODE RANGE = STRUCT(INT lwb, upb);
<syntaxhighlight 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 183: Line 183:
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 ", whole(lwb OF range, 0), " to ",whole(upb OF range, 0)," is ", fixed(SHORTEN sum(f,range),-8,5),".", 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))
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 191: Line 191:
=={{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.
<lang algolw>begin % compute the sum of 1/k^2 for k = 1..1000 %
<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 206: 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.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 213: Line 213:


=={{header|APL}}==
=={{header|APL}}==
<lang APL> +/÷2*⍨⍳1000
<syntaxhighlight lang="apl"> +/÷2*⍨⍳1000
1.64393</lang>
1.64393</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|JavaScript}}
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang AppleScript>----------------------- SUM OF SERIES ----------------------
<syntaxhighlight lang="applescript">----------------------- SUM OF SERIES ----------------------


-- seriesSum :: Num a => (a -> a) -> [a] -> a
-- seriesSum :: Num a => (a -> a) -> [a] -> a
Line 287: Line 287:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>1.643934566682</lang>
<syntaxhighlight lang="applescript">1.643934566682</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>series: map 1..1000 => [1.0/&^2]
<syntaxhighlight lang="rebol">series: map 1..1000 => [1.0/&^2]
print [sum series]</lang>
print [sum series]</syntaxhighlight>


{{out}}
{{out}}
Line 301: Line 301:
=={{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.
<lang autohotkey>SetFormat, FloatFast, 0.15
<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</lang>
MsgBox,% sum ;1.643934566681554</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}'
<syntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}'
1.64393</lang>
1.64393</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>function s(x%)
<syntaxhighlight lang="qbasic">function s(x%)
s = 1 / x ^ 2
s = 1 / x ^ 2
end function
end function
Line 323: Line 323:
sum = ret
sum = ret
end function
end function
print sum(1, 1000)</lang>
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 340: Line 340:
print "zeta(2) = "; pi * pi / 6
print "zeta(2) = "; pi * pi / 6
end
end
</syntaxhighlight>
</lang>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> FOR i% = 1 TO 1000
<syntaxhighlight lang="bbcbasic"> FOR i% = 1 TO 1000
sum += 1/i%^2
sum += 1/i%^2
NEXT
NEXT
PRINT sum</lang>
PRINT sum</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{works with|BASIC256}}
{{works with|BASIC256}}
<lang qbasic>
<syntaxhighlight lang="qbasic">
FUNCTION sumSeries(n)
FUNCTION sumSeries(n)
IF n = 0 then
IF n = 0 then
Line 365: Line 365:
PRINT "zeta(2) = "; pi * pi / 6
PRINT "zeta(2) = "; pi * pi / 6
END
END
</syntaxhighlight>
</lang>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>
<syntaxhighlight lang="yabasic">
sub sumSeries(n)
sub sumSeries(n)
if n = 0 then return 0 : fi
if n = 0 then return 0 : fi
Line 381: Line 381:
print "zeta(2) = ", pi * pi / 6
print "zeta(2) = ", pi * pi / 6
end
end
</syntaxhighlight>
</lang>


=={{header|bc}}==
=={{header|bc}}==
<lang bc>define f(x) {
<syntaxhighlight lang="bc">define f(x) {
return(1 / (x * x))
return(1 / (x * x))
}
}
Line 399: Line 399:


scale = 20
scale = 20
s(1000)</lang>
s(1000)</syntaxhighlight>


{{Out}}
{{Out}}
Line 405: Line 405:


=={{header|Beads}}==
=={{header|Beads}}==
<lang Beads>beads 1 program 'Sum of a series'
<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)</lang>
log to_str(k)</syntaxhighlight>
{{out}}
{{out}}
<pre>1.6439345666815615</pre>
<pre>1.6439345666815615</pre>
Line 416: Line 416:
=={{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.
<lang befunge>05558***>::"~"%00p"~"/10p"( }}2"*v
<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-:#^_$</lang>
"."\55+%68^>\55+/00g1-:#^_$</syntaxhighlight>
{{out}}
{{out}}
<pre>1.643934</pre>
<pre>1.643934</pre>
Line 427: Line 427:
<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.
<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.


<lang bqn> +´÷√⁼1+↕1000
<syntaxhighlight lang="bqn"> +´÷√⁼1+↕1000
1.6439345666815597</lang>
1.6439345666815597</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( 0:?i
<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))
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>8354593848314...../5082072010432..... (1732 digits and a slash)
<pre>8354593848314...../5082072010432..... (1732 digits and a slash)
Line 442: Line 442:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816</lang>
<syntaxhighlight lang="brat">p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


double Invsqr(double n)
double Invsqr(double n)
Line 463: Line 463:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>class Program
<syntaxhighlight lang="csharp">class Program
{
{
static void Main(string[] args)
static void Main(string[] args)
Line 484: Line 484:
Console.ReadLine();
Console.ReadLine();
}
}
}</lang>
}</syntaxhighlight>


An alternative approach using Enumerable.Range() to generate the numbers.
An alternative approach using Enumerable.Range() to generate the numbers.


<lang csharp>class Program
<syntaxhighlight lang="csharp">class Program
{
{
static void Main(string[] args)
static void Main(string[] args)
Line 497: Line 497:
Console.ReadLine();
Console.ReadLine();
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


double f(double x);
double f(double x);
Line 522: Line 522:
{
{
return ( 1.0 / ( x * x ) );
return ( 1.0 / ( x * x ) );
}</lang>
}</syntaxhighlight>


=={{header|CLIPS}}==
=={{header|CLIPS}}==
<lang clips>(deffunction S (?x) (/ 1 (* ?x ?x)))
<syntaxhighlight lang="clips">(deffunction S (?x) (/ 1 (* ?x ?x)))
(deffunction partial-sum-S
(deffunction partial-sum-S
(?start ?stop)
(?start ?stop)
Line 533: Line 533:
)
)
(return ?sum)
(return ?sum)
)</lang>
)</syntaxhighlight>


Usage:
Usage:
Line 540: Line 540:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(reduce + (map #(/ 1.0 % %) (range 1 1001)))</lang>
<syntaxhighlight lang="clojure">(reduce + (map #(/ 1.0 % %) (range 1 1001)))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>series_sum = proc (from, to: int,
<syntaxhighlight lang="clu">series_sum = proc (from, to: int,
fn: proctype (real) returns (real))
fn: proctype (real) returns (real))
returns (real)
returns (real)
Line 561: Line 561:
result: real := series_sum(1, 1000, one_over_k_squared)
result: real := series_sum(1, 1000, one_over_k_squared)
stream$putl(po, f_form(result, 1, 6))
stream$putl(po, f_form(result, 1, 6))
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>1.643935</pre>
<pre>1.643935</pre>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. sum-of-series.
PROGRAM-ID. sum-of-series.


Line 584: Line 584:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 591: Line 591:


=={{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}}==
<lang lisp>(loop for x from 1 to 1000 summing (expt x -2))</lang>
<syntaxhighlight lang="lisp">(loop for x from 1 to 1000 summing (expt x -2))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>puts (1..1000).sum{ |x| 1.0 / x ** 2 }
<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</lang>
puts Math::PI ** 2 / 6</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 614: Line 614:
=={{header|D}}==
=={{header|D}}==
===More Procedural Style===
===More Procedural Style===
<lang d>import std.stdio, std.traits;
<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 626: Line 626:
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));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Sum: 1.64393</pre>
<pre>Sum: 1.64393</pre>
Line 632: Line 632:
===More functional Style===
===More functional Style===
Same output.
Same output.
<lang d>import std.stdio, std.algorithm, std.range;
<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 639: Line 639:
void main() {
void main() {
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000));
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000));
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
{{trans|Scala}}
{{trans|Scala}}
<lang dart>main() {
<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 652: Line 652:
});
});
print(sum);
print(sum);
}</lang>
}</syntaxhighlight>


{{trans|F#}}
{{trans|F#}}
<lang dart>f(double x) {
<syntaxhighlight lang="dart">f(double x) {
if (x == 0)
if (x == 0)
return x;
return x;
Line 664: Line 664:
main() {
main() {
print(f(1000));
print(f(1000));
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Form_SumOfASeries_Unit;
unit Form_SumOfASeries_Unit;


Line 715: Line 715:
end.
end.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>1.64393456668156</pre>
<pre>1.64393456668156</pre>
Line 721: Line 721:
=={{header|DWScript}}==
=={{header|DWScript}}==


<lang delphi>
<syntaxhighlight lang="delphi">
var s : Float;
var s : Float;
for var i := 1 to 1000 do
for var i := 1 to 1000 do
Line 727: Line 727:


PrintLn(s);
PrintLn(s);
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 733: Line 733:
{{trans|Swift}}
{{trans|Swift}}


<lang dyalect>func Integer.SumSeries() {
<syntaxhighlight lang="dyalect">func Integer.SumSeries() {
var ret = 0
var ret = 0


Line 744: Line 744:
var x = 1000
var x = 1000
print(x.SumSeries())</lang>
print(x.SumSeries())</syntaxhighlight>


{{out}}
{{out}}
Line 752: Line 752:
=={{header|E}}==
=={{header|E}}==


<lang e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }</lang>
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<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 765: Line 765:
(// (* PI PI) 6)
(// (* PI PI) 6)
→ 1.6449340668482264
→ 1.6449340668482264
</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
Line 771: Line 771:


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.
<lang edsac>
<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 834: Line 834:
[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 842: Line 842:


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang 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 894: Line 894:
end
end


</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 906: Line 906:
console.printLine:sum
console.printLine:sum
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 913: Line 913:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end)
<syntaxhighlight lang="elixir">iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end)
1.6439345666815615</lang>
1.6439345666815615</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(defun series (n)
<syntaxhighlight lang="lisp">(defun series (n)
(when (<= n 0)
(when (<= n 0)
(user-error "n must be positive"))
(user-error "n must be positive"))
(apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))
(apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))


(format "%.10f" (series 1000)) ;=> "1.6439345667"</lang>
(format "%.10f" (series 1000)) ;=> "1.6439345667"</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==


<lang erlang>lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]).</lang>
<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 944: Line 944:
end function
end function


printf( 1, "%.15f\n", sum( 1, 1000 ) )</lang>
printf( 1, "%.15f\n", sum( 1, 1000 ) )</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
Line 956: Line 956:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>sumOfSeries
<syntaxhighlight lang="lisp">sumOfSeries
=LAMBDA(f,
=LAMBDA(f,
LAMBDA(n,
LAMBDA(n,
Line 969: Line 969:
=LAMBDA(n,
=LAMBDA(n,
1 / (n ^ 2)
1 / (n ^ 2)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,003: Line 1,003:


=={{header|Ezhil}}==
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது


Line 1,029: Line 1,029:
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)


</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.
<lang fsharp>let rec f (x : float) =
<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.)</lang>
| 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:
<lang fsharp>> f 1000. ;;
<syntaxhighlight lang="fsharp">> f 1000. ;;
val it : float = 1.643934567</lang>
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:
<lang fsharp>#light
<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 1,053: Line 1,053:
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</lang>
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:
<lang fsharp>
<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}}==
<lang factor>1000 [1,b] [ >float sq recip ] map-sum</lang>
<syntaxhighlight lang="factor">1000 [1,b] [ >float sq recip ] map-sum</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,068: Line 1,068:
Within 'fansh':
Within 'fansh':


<lang fantom>
<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}}==
<lang fermat>Sigma<k=1,1000>[1/k^2]</lang>
<syntaxhighlight lang="fermat">Sigma<k=1,1000>[1/k^2]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,095: Line 1,095:


=={{header|Fish}}==
=={{header|Fish}}==
<lang fish>0&aaa**>::*1$,&v
<syntaxhighlight lang="fish">0&aaa**>::*1$,&v
;n&^?:-1&+ <</lang>
;n&^?:-1&+ <</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: sum ( fn start count -- fsum )
<syntaxhighlight lang="forth">: sum ( fn start count -- fsum )
0e
0e
bounds do
bounds do
Line 1,107: Line 1,107:
: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</lang>
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:
<lang fortran>real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /)
<syntaxhighlight lang="fortran">real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /)
real :: result
real :: result


result = sum(a);</lang>
result = sum(a);</syntaxhighlight>
Or in Fortran 77:
Or in Fortran 77:
<lang fortran> s=0
<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</lang>
end</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Const pi As Double = 3.141592653589793
Const pi As Double = 3.141592653589793
Line 1,141: Line 1,141:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,151: Line 1,151:
=={{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.
<lang frink>
<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,169: Line 1,169:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># We will compute the sum exactly
<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,200: Line 1,200:
Approx(a, 10);
Approx(a, 10);
"1.6439345666"
"1.6439345666"
# and pi^2/6 is 1.6449340668, truncated to ten digits</lang>
# and pi^2/6 is 1.6449340668, truncated to ten digits</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Sum of series, in Genie
Sum of series, in Genie
Line 1,224: Line 1,224:
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</lang>
print "π² / 6 : %16.15f", Math.PI * Math.PI / 6.0</syntaxhighlight>


{{out}}
{{out}}
Line 1,233: Line 1,233:


=={{header|GEORGE}}==
=={{header|GEORGE}}==
<syntaxhighlight lang="george">
<lang GEORGE>
0 (s)
0 (s)
1, 1000 rep (i)
1, 1000 rep (i)
Line 1,239: Line 1,239:
]
]
P
P
</syntaxhighlight>
</lang>
Output:-
Output:-
<pre>
<pre>
Line 1,246: Line 1,246:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import ("fmt"; "math")
import ("fmt"; "math")
Line 1,257: Line 1,257:
}
}
fmt.Println("computed:", sum)
fmt.Println("computed:", sum)
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>known: 1.6449340668482264
<pre>known: 1.6449340668482264
Line 1,264: Line 1,264:
=={{header|Groovy}}==
=={{header|Groovy}}==
Start with smallest terms first to minimize rounding error:
Start with smallest terms first to minimize rounding error:
<lang groovy>println ((1000..1).collect { x -> 1/(x*x) }.sum())</lang>
<syntaxhighlight lang="groovy">println ((1000..1).collect { x -> 1/(x*x) }.sum())</syntaxhighlight>


Output:
Output:
Line 1,271: Line 1,271:
=={{header|Haskell}}==
=={{header|Haskell}}==
With a list comprehension:
With a list comprehension:
<lang haskell>sum [1 / x ^ 2 | x <- [1..1000]]</lang>
<syntaxhighlight lang="haskell">sum [1 / x ^ 2 | x <- [1..1000]]</syntaxhighlight>
With higher-order functions:
With higher-order functions:
<lang haskell>sum $ map (\x -> 1 / x ^ 2) [1..1000]</lang>
<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:
<lang haskell>(sum . map (1/) . map (^2)) [1..1000]</lang>
<syntaxhighlight lang="haskell">(sum . map (1/) . map (^2)) [1..1000]</syntaxhighlight>
or
or
<lang haskell>(sum . map ((1 /) . (^ 2))) [1 .. 1000]</lang>
<syntaxhighlight lang="haskell">(sum . map ((1 /) . (^ 2))) [1 .. 1000]</syntaxhighlight>


or, as a single fold:
or, as a single fold:


<lang haskell>seriesSum f = foldr ((+) . f) 0
<syntaxhighlight lang="haskell">seriesSum f = foldr ((+) . f) 0


inverseSquare = (1 /) . (^ 2)
inverseSquare = (1 /) . (^ 2)


main :: IO ()
main :: IO ()
main = print $ seriesSum inverseSquare [1 .. 1000]</lang>
main = print $ seriesSum inverseSquare [1 .. 1000]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>1.6439345666815615</pre>
<pre>1.6439345666815615</pre>
Line 1,292: Line 1,292:
=={{header|Haxe}}==
=={{header|Haxe}}==
===Procedural===
===Procedural===
<lang haxe>using StringTools;
<syntaxhighlight lang="haxe">using StringTools;


class Main {
class Main {
Line 1,302: Line 1,302:
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,311: Line 1,311:


===Functional===
===Functional===
<lang haxe>using Lambda;
<syntaxhighlight lang="haxe">using Lambda;
using StringTools;
using StringTools;


Line 1,320: Line 1,320:
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,326: Line 1,326:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>REAL :: a(1000)
<syntaxhighlight lang="hicest">REAL :: a(1000)
a = 1 / $^2
a = 1 / $^2
WRITE(ClipBoard, Format='F17.15') SUM(a) </lang>
WRITE(ClipBoard, Format='F17.15') SUM(a) </syntaxhighlight>
<lang hicest>1.643934566681561</lang>
<syntaxhighlight lang="hicest">1.643934566681561</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>procedure main()
<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</lang>
end</syntaxhighlight>


or
or


<lang icon>procedure main()
<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</lang>
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:
<lang icon>
<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}}==


<lang idl>print,total( 1/(1+findgen(1000))^2)</lang>
<syntaxhighlight lang="idl">print,total( 1/(1+findgen(1000))^2)</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
Line 1,367: Line 1,367:


=={{header|J}}==
=={{header|J}}==
<lang j> NB. sum of reciprocals of squares of first thousand positive integers
<syntaxhighlight lang="j"> NB. sum of reciprocals of squares of first thousand positive integers
+/ % *: >: i. 1000
+/ % *: >: i. 1000
1.64393
1.64393
Line 1,375: Line 1,375:
1r6p2 NB. As a constant (J has a rich constant notation)
1r6p2 NB. As a constant (J has a rich constant notation)
1.64493</lang>
1.64493</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class Sum{
<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,392: Line 1,392:
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);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>function sum(a,b,fn) {
<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,402: Line 1,402:
}
}
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156</lang>
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156</syntaxhighlight>


or, in a functional idiom:
or, in a functional idiom:


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


function sum(fn, lstRange) {
function sum(fn, lstRange) {
Line 1,430: Line 1,430:
);
);


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}


<lang JavaScript>1.6439345666815615</lang>
<syntaxhighlight lang="javascript">1.6439345666815615</syntaxhighlight>


===ES6===
===ES6===
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,462: Line 1,462:


return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000));
return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000));
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<lang JavaScript>1.6439345666815615</lang>
<syntaxhighlight lang="javascript">1.6439345666815615</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,470: Line 1,470:


Directly:
Directly:
<lang jq>def s(n): reduce range(1; n+1) as $k (0; . + 1/($k * $k) );
<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,479: Line 1,479:
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:


<lang jq>def summation(s): reduce s as $k (0; . + $k);
<syntaxhighlight lang="jq">def summation(s): reduce s as $k (0; . + $k);


summation( range(1; 1001) | (1/(. * .) ) )</lang>
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,488: Line 1,488:
From Javascript ES5.
From Javascript ES5.


<lang javascript>#!/usr/bin/jsish
<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,502: Line 1,502:
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,511: Line 1,511:
Using a higher-order function:
Using a higher-order function:


<lang Julia>julia> sum(k -> 1/k^2, 1:1000)
<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:


<lang Julia>julia> function f(n)
<syntaxhighlight lang="julia">julia> function f(n)
s = 0.0
s = 0.0
for k = 1:n
for k = 1:n
Line 1,529: Line 1,529:


julia> f(1000)
julia> f(1000)
1.6439345666815615</lang>
1.6439345666815615</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<lang k> ssr: +/1%_sqr
<syntaxhighlight lang="k"> ssr: +/1%_sqr
ssr 1+!1000
ssr 1+!1000
1.643935</lang>
1.643935</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,544: Line 1,544:
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}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,553: Line 1,553:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang lisp>
<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}}==
<lang lang5>1000 iota 1 + 1 swap / 2 ** '+ reduce .</lang>
<syntaxhighlight lang="lang5">1000 iota 1 + 1 swap / 2 ** '+ reduce .</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define sum_of_a_series(n::integer,k::integer) => {
<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,569: Line 1,569:
return #sum
return #sum
}
}
sum_of_a_series(1000,1)</lang>
sum_of_a_series(1000,1)</syntaxhighlight>
{{out}}
{{out}}
<pre>1.643935</pre>
<pre>1.643935</pre>
Line 1,577: Line 1,577:
=== With <code>lists:foldl</code> ===
=== With <code>lists:foldl</code> ===


<lang lisp>
<syntaxhighlight lang="lisp">
(defun sum-series (nums)
(defun sum-series (nums)
(lists:foldl
(lists:foldl
Line 1,585: Line 1,585:
(lambda (x) (/ 1 x x))
(lambda (x) (/ 1 x x))
nums)))
nums)))
</syntaxhighlight>
</lang>


=== With <code>lists:sum</code> ===
=== With <code>lists:sum</code> ===


<lang lisp>
<syntaxhighlight lang="lisp">
(defun sum-series (nums)
(defun sum-series (nums)
(lists:sum
(lists:sum
Line 1,595: Line 1,595:
(lambda (x) (/ 1 x x))
(lambda (x) (/ 1 x x))
nums)))
nums)))
</syntaxhighlight>
</lang>


Both have the same result:
Both have the same result:


<lang lisp>
<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,613: Line 1,613:


end
end
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>the floatprecision = 8
<syntaxhighlight lang="lingo">the floatprecision = 8
sum = 0
sum = 0
repeat with i = 1 to 1000
repeat with i = 1 to 1000
Line 1,622: Line 1,622:
end repeat
end repeat
put sum
put sum
-- 1.64393457</lang>
-- 1.64393457</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>repeat with i = 1 to 1000
<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</lang>
put summ //1.643935</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to series :fn :a :b
<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,641: Line 1,641:
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</lang>
print :pi * :pi / 6</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang 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}}==
<lang lucid>series = ssum asa n >= 1000
<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;</lang>
end;</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>sum(1/k^2, k=1..1000);</lang>
<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>
Line 1,664: Line 1,664:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This is the straightforward solution of the task:
This is the straightforward solution of the task:
<lang mathematica>Sum[1/x^2, {x, 1, 1000}]</lang>
<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>:
<lang mathematica>N[Sum[1/x^2, {x, 1, 1000}]]</lang>
<syntaxhighlight lang="mathematica">N[Sum[1/x^2, {x, 1, 1000}]]</syntaxhighlight>
or better:
or better:
<lang mathematica>NSum[1/x^2, {x, 1, 1000}]</lang>
<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:
<lang mathematica>Sum[1./x^2, {x, 1, 1000}]</lang>
<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):
<lang mathematica>Total[Table[1/x^2, {x, 1, 1000}]]
<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}]</lang>
Plus@@Table[1./x^2, {x, 1, 1000}]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang matlab> sum([1:1000].^(-2)) </lang>
<syntaxhighlight lang="matlab"> sum([1:1000].^(-2)) </syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==


<lang maxima>(%i45) sum(1/x^2, x, 1, 1000);
<syntaxhighlight lang="maxima">(%i45) sum(1/x^2, x, 1, 1000);
835459384831496894781878542648[806 digits]396236858699094240207812766449
835459384831496894781878542648[806 digits]396236858699094240207812766449
(%o45) ------------------------------------------------------------------------
(%o45) ------------------------------------------------------------------------
Line 1,688: Line 1,688:


(%i46) sum(1/x^2, x, 1, 1000),numer;
(%i46) sum(1/x^2, x, 1, 1000),numer;
(%o46) 1.643934566681561</lang>
(%o46) 1.643934566681561</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>total = 0
<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</lang>
print total</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>0 1 (
<syntaxhighlight lang="min">0 1 (
((dup * 1 swap /) (id)) cleave
((dup * 1 swap /) (id)) cleave
((+) (succ)) spread
((+) (succ)) spread
) 1000 times pop print</lang>
) 1000 times pop print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,710: Line 1,710:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>zeta = function(num)
<syntaxhighlight lang="miniscript">zeta = function(num)
return 1 / num^2
return 1 / num^2
end function
end function
Line 1,723: Line 1,723:


print sum(1, 1000, @zeta)
print sum(1, 1000, @zeta)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,730: Line 1,730:


=={{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 С/П</lang>
ИП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}}===
<lang ocaml>println ` fold (+, 0) ` map (fn x = 1 / x ^ 2) ` iota (1,1000);</lang>
<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}}==
<lang mmix>x IS $1 % flt calculations
<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,853: Line 1,853:
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</lang>
TRAP 0,Halt,0</syntaxhighlight>
Output:
Output:
<pre>~/MIX/MMIX/Rosetta> mmix sumseries
<pre>~/MIX/MMIX/Rosetta> mmix sumseries
Line 1,859: Line 1,859:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE SeriesSum;
<syntaxhighlight lang="modula2">MODULE SeriesSum;
FROM InOut IMPORT WriteLn;
FROM InOut IMPORT WriteLn;
FROM RealInOut IMPORT WriteReal;
FROM RealInOut IMPORT WriteReal;
Line 1,884: Line 1,884:
WriteReal(seriesSum(1, 1000, oneOverKSquared), 10);
WriteReal(seriesSum(1, 1000, oneOverKSquared), 10);
WriteLn;
WriteLn;
END SeriesSum.</lang>
END SeriesSum.</syntaxhighlight>
{{out}}
{{out}}
<pre>1.6439E+00</pre>
<pre>1.6439E+00</pre>
Line 1,890: Line 1,890:
=={{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>.
<lang modula3>MODULE Sum EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Sum EXPORTS Main;


IMPORT IO, Fmt, Math;
IMPORT IO, Fmt, Math;
Line 1,908: Line 1,908:
IO.Put(Fmt.LongReal(sum));
IO.Put(Fmt.LongReal(sum));
IO.Put("\n");
IO.Put("\n");
END Sum.</lang>
END Sum.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,915: Line 1,915:


=={{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,921: Line 1,921:
.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,929: Line 1,929:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(let (s 0)
<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))</lang>
(println s))</syntaxhighlight>


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>|sum (1 / power (count 1000) 2)
<syntaxhighlight lang="nial">|sum (1 / power (count 1000) 2)
=1.64393</lang>
=1.64393</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>var s = 0.0
<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</lang>
echo s</syntaxhighlight>


{{out}}
{{out}}
Line 1,947: Line 1,947:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class SumSeries {
class SumSeries {
Line 1,972: Line 1,972:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let sum a b fn =
<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</lang>
!result</syntaxhighlight>


# sum 1 1000 (fun x -> 1. /. (float x ** 2.))
# sum 1 1000 (fun x -> 1. /. (float x ** 2.))
Line 1,986: Line 1,986:


or in a functional programming style:
or in a functional programming style:
<lang ocaml>let sum a b fn =
<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,992: Line 1,992:
in
in
aux a 0.
aux a 0.
;;</lang>
;;</syntaxhighlight>
Simple recursive solution:
Simple recursive solution:
<lang ocaml>let rec sum n = if n < 1 then 0.0 else sum (n-1) +. 1.0 /. float (n*n)
<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</lang>
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:


<lang octave>sum(1 ./ [1:1000] .^ 2)</lang>
<syntaxhighlight lang="octave">sum(1 ./ [1:1000] .^ 2)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: sumSerie(s, n) 0 n seq apply(#[ s perform + ]) ;</lang>
<syntaxhighlight lang="oforth">: sumSerie(s, n) 0 n seq apply(#[ s perform + ]) ;</syntaxhighlight>


Usage :
Usage :
<lang Oforth> #[ sq inv ] 1000 sumSerie println</lang>
<syntaxhighlight lang="oforth"> #[ sq inv ] 1000 sumSerie println</syntaxhighlight>


{{out}}
{{out}}
Line 2,018: Line 2,018:
Conventionally like elsewhere:
Conventionally like elsewhere:


<lang Progress (Openedge ABL)>def var dcResult as decimal no-undo.
<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 2,025: Line 2,025:
end.
end.


display dcResult .</lang>
display dcResult .</syntaxhighlight>


or like this:
or like this:


<lang Progress (Openedge ABL)>def var n as int no-undo.
<syntaxhighlight lang="progress (openedge abl)">def var n as int no-undo.


repeat n = 1 to 1000 :
repeat n = 1 to 1000 :
Line 2,035: Line 2,035:
end.
end.


display ( accum total 1 / (n * n) ) .</lang>
display ( accum total 1 / (n * n) ) .</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
With higher-order functions:
With higher-order functions:
<lang oz>declare
<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 2,049: Line 2,049:
end
end
in
in
{Show {SumSeries S 1000}}</lang>
{Show {SumSeries S 1000}}</syntaxhighlight>


Iterative:
Iterative:
<lang oz> fun {SumSeries S N}
<syntaxhighlight lang="oz"> fun {SumSeries S N}
R = {NewCell 0.}
R = {NewCell 0.}
in
in
Line 2,059: Line 2,059:
end
end
@R
@R
end</lang>
end</syntaxhighlight>


=={{header|Panda}}==
=={{header|Panda}}==
<lang panda>sum{{1.0.divide(1..1000.sqr)}}</lang>
<syntaxhighlight lang="panda">sum{{1.0.divide(1..1000.sqr)}}</syntaxhighlight>
Output:
Output:
<pre>1.6439345666815615</pre>
<pre>1.6439345666815615</pre>
Line 2,068: Line 2,068:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Exact rational solution:
Exact rational solution:
<lang parigp>sum(n=1,1000,1/n^2)</lang>
<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):
<lang parigp>sum(n=1,1000,1./n^2)</lang>
<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):
<lang parigp>zeta(2)-intnum(x=1000.5,[1],1/x^2)</lang>
<syntaxhighlight lang="parigp">zeta(2)-intnum(x=1000.5,[1],1/x^2)</syntaxhighlight>
or
or
<lang parigp>zeta(2)-1/1000.5</lang>
<syntaxhighlight lang="parigp">zeta(2)-1/1000.5</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program SumSeries;
<syntaxhighlight lang="pascal">Program SumSeries;
type
type
tOutput = double;//extended;
tOutput = double;//extended;
Line 2,102: Line 2,102:
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.</lang>
end.</syntaxhighlight>
Output
Output
<pre>different version of type and calculation
<pre>different version of type and calculation
Line 2,115: Line 2,115:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my $sum = 0;
<syntaxhighlight lang="perl">my $sum = 0;
$sum += 1 / $_ ** 2 foreach 1..1000;
$sum += 1 / $_ ** 2 foreach 1..1000;
print "$sum\n";</lang>
print "$sum\n";</syntaxhighlight>
or
or
<lang perl>use List::Util qw(reduce);
<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";</lang>
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:
<lang perl>my $S = do { my ($sum, $k); sub { $sum += 1/++$k**2 } };
<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];</lang>
print $S[-1];</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<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,137: Line 2,137:
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,144: Line 2,144:


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP><?php
<syntaxhighlight lang="php"><?php


/**
/**
Line 2,166: Line 2,166:


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>
Line 2,172: Line 2,172:
=={{header|Picat}}==
=={{header|Picat}}==
===List comprehension===
===List comprehension===
<lang Picat>s(N) = sum([1.0/K**2 : K in 1..N]).</lang>
<syntaxhighlight lang="picat">s(N) = sum([1.0/K**2 : K in 1..N]).</syntaxhighlight>


===Iterative===
===Iterative===
<lang Picat>s2(N) = Sum =>
<syntaxhighlight lang="picat">s2(N) = Sum =>
K = 1,
K = 1,
Sum1 = 0,
Sum1 = 0,
Line 2,182: Line 2,182:
K := K + 1
K := K + 1
end,
end,
Sum = Sum1.</lang>
Sum = Sum1.</syntaxhighlight>


===Test===
===Test===
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
% List comprehension
% List comprehension
test(s,1000),
test(s,1000),
Line 2,202: Line 2,202:
printf("%f (diff: %w)\n", S,Pi2_6-S)
printf("%f (diff: %w)\n", S,Pi2_6-S)
end,
end,
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 2,226: Line 2,226:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 9) # Calculate with 9 digits precision
<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</lang>
(prinl (round S 6)) ) # Round result to 6 digits</syntaxhighlight>
Output:
Output:
<pre>1.643935</pre>
<pre>1.643935</pre>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>array(int) x = enumerate(1000,1,1);
<syntaxhighlight lang="pike">array(int) x = enumerate(1000,1,1);
`+(@(1.0/pow(x[*],2)[*]));
`+(@(1.0/pow(x[*],2)[*]));
Result: 1.64393</lang>
Result: 1.64393</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>/* sum the first 1000 terms of the series 1/n**2. */
<syntaxhighlight lang="pli">/* sum the first 1000 terms of the series 1/n**2. */
s = 0;
s = 0;


Line 2,248: Line 2,248:
end;
end;


put skip list (s);</lang>
put skip list (s);</syntaxhighlight>


{{out}}
{{out}}
Line 2,257: Line 2,257:
=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>lvars s = 0, j;
<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 =></lang>
s =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang>
<syntaxhighlight lang="text">
/aproxriemann{
/aproxriemann{
/x exch def
/x exch def
Line 2,278: Line 2,278:


1000 aproxriemann
1000 aproxriemann
</syntaxhighlight>
</lang>
Output:
Output:
<lang>
<syntaxhighlight lang="text">
1.64393485
1.64393485
</syntaxhighlight>
</lang>


{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<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,291: Line 2,291:
% 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}}==
<lang potion>sum = 0.0
<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</lang>
sum print</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$x = 1..1000 `
<syntaxhighlight lang="powershell">$x = 1..1000 `
| ForEach-Object { 1 / ($_ * $_) } `
| ForEach-Object { 1 / ($_ * $_) } `
| Measure-Object -Sum
| Measure-Object -Sum
Write-Host Sum = $x.Sum</lang>
Write-Host Sum = $x.Sum</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>sum(S) :-
<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,316: Line 2,316:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Define i, sum.d
<syntaxhighlight lang="purebasic">Define i, sum.d


For i=1 To 1000
For i=1 To 1000
Line 2,322: Line 2,322:
Next i
Next i


Debug sum</lang>
Debug sum</syntaxhighlight>
<tt>
<tt>
Answer = 1.6439345666815615
Answer = 1.6439345666815615
Line 2,328: Line 2,328:


=={{header|Python}}==
=={{header|Python}}==
<lang python>print ( sum(1.0 / (x * x) for x in range(1, 1001)) )</lang>
<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]]):
<lang python>'''The sum of a series'''
<syntaxhighlight lang="python">'''The sum of a series'''


from functools import reduce
from functools import reduce
Line 2,403: Line 2,403:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>The sum of a series:
<pre>The sum of a series:
Line 2,411: Line 2,411:


=={{header|Q}}==
=={{header|Q}}==
<lang q>sn:{sum xexp[;-2] 1+til x}
<syntaxhighlight lang="q">sn:{sum xexp[;-2] 1+til x}
sn 1000</lang>
sn 1000</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,421: Line 2,421:
Using the Quackery bignum rational arithmetic suite <code>bigrat.qky</code>.
Using the Quackery bignum rational arithmetic suite <code>bigrat.qky</code>.


<lang Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!


[ 0 n->v rot times
[ 0 n->v rot times
Line 2,438: Line 2,438:
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$</lang>
1000 point$ echo$</syntaxhighlight>


{{out}}
{{out}}
Line 2,453: Line 2,453:


=={{header|R}}==
=={{header|R}}==
<lang r>print( sum( 1/seq(1000)^2 ) )</lang>
<syntaxhighlight lang="r">print( sum( 1/seq(1000)^2 ) )</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,459: Line 2,459:
A solution using Typed Racket:
A solution using Typed Racket:


<lang racket>
<syntaxhighlight lang="racket">
#lang typed/racket
#lang typed/racket


Line 2,466: Line 2,466:
(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,474: Line 2,474:
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 perl6>[+] map &f, 1 .. $n</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 perl6>say [+] map { 1 / $^n**2 }, 1 .. 1000;</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 perl6>say [+] 1 «/« (1..1000) »**» 2;</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 perl6>say [+] 1 X/ (1..1000 X** 2);</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 perl6>say [+] (1 / $_**2 for 1..1000);</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 perl6>constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *;
<syntaxhighlight lang="raku" line>constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *;
say @x[1000]; # prints 1.64393456668156</lang>
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 perl6>constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*;
<syntaxhighlight lang="raku" line>constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*;
say ζish[1000];</lang>
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 perl6>use experimental :cached;
<syntaxhighlight lang="raku" line>use experimental :cached;
sub ζ($s) is cached { [\+] 1..* X** -$s }
sub ζ($s) is cached { [\+] 1..* X** -$s }
say ζ(2)[1000];</lang>
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}}==
<lang Raven>0 1 1000 1 range each 1.0 swap dup * / +
<syntaxhighlight lang="raven">0 1 1000 1 range each 1.0 swap dup * / +
"%g\n" print</lang>
"%g\n" print</syntaxhighlight>
{{out}}
{{out}}
<pre>1.64393</pre>
<pre>1.64393</pre>
Line 2,518: Line 2,518:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>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===
<lang rexx>/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */
<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,536: Line 2,536:
end /*k*/
end /*k*/


say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */</lang>
say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the default input:
'''output''' &nbsp; when using the default input:
<pre>
<pre>
Line 2,544: Line 2,544:
===sums with running total===
===sums with running total===
This REXX version shows the &nbsp; ''running total'' &nbsp; for every 10<sup>th</sup> term.
This REXX version shows the &nbsp; ''running total'' &nbsp; for every 10<sup>th</sup> term.
<lang rexx>/*REXX program sums the first N terms o f 1/(k**2), k=1 ──► N. */
<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,562: Line 2,562:
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. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the input of: &nbsp; <tt> 1000000000 </tt>
'''output''' &nbsp; when using the input of: &nbsp; <tt> 1000000000 </tt>
<pre>
<pre>
Line 2,585: Line 2,585:


If the &nbsp; '''old''' &nbsp; REXX variable would be set to &nbsp; '''1.64''' &nbsp; (instead of &nbsp; '''1'''), the first noise digits could be bypassed to make the display ''cleaner''.
If the &nbsp; '''old''' &nbsp; REXX variable would be set to &nbsp; '''1.64''' &nbsp; (instead of &nbsp; '''1'''), the first noise digits could be bypassed to make the display ''cleaner''.
<lang rexx>/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */
<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,605: Line 2,605:
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. */</lang>
say $ /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the input of &nbsp; (one billion [limit], and one hundred decimal digits): &nbsp; <tt> &nbsp; 1000000000 &nbsp; 100 </tt>
'''output''' &nbsp; when using the input of &nbsp; (one billion [limit], and one hundred decimal digits): &nbsp; <tt> &nbsp; 1000000000 &nbsp; 100 </tt>
<pre>
<pre>
Line 2,633: Line 2,633:


=={{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,640: Line 2,640:
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|Ruby}}==
=={{header|Ruby}}==
<lang ruby>puts (1..1000).inject{ |sum, x| sum + 1.0 / x ** 2 }</lang>
<syntaxhighlight lang="ruby">puts (1..1000).inject{ |sum, x| sum + 1.0 / x ** 2 }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,656: Line 2,656:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>
<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</lang>
print sum</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>const LOWER: i32 = 1;
<syntaxhighlight lang="rust">const LOWER: i32 = 1;
const UPPER: i32 = 1000;
const UPPER: i32 = 1000;


Line 2,675: Line 2,675:
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}}==
<lang sas>data _null_;
<syntaxhighlight lang="sas">data _null_;
s=0;
s=0;
do n=1 to 1000;
do n=1 to 1000;
Line 2,685: Line 2,685:
e=s-constant('pi')**2/6;
e=s-constant('pi')**2/6;
put s e;
put s e;
run;</lang>
run;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>scala> 1 to 1000 map (x => 1.0 / (x * x)) sum
<syntaxhighlight lang="scala">scala> 1 to 1000 map (x => 1.0 / (x * x)) sum
res30: Double = 1.6439345666815615</lang>
res30: Double = 1.6439345666815615</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (sum a b fn)
<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,698: Line 2,698:


(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</lang>
(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:
<lang scheme>(define (invsq f to)
<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,709: Line 2,709:
;; 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</lang>
(exact->inexact (invsq 1 1000)) ; 1.64393456668156</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 2,727: Line 2,727:
end for;
end for;
writeln(sum digits 6 lpad 8);
writeln(sum digits 6 lpad 8);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say sum(1..1000, {|n| 1 / n**2 })</lang>
<syntaxhighlight lang="ruby">say sum(1..1000, {|n| 1 / n**2 })</syntaxhighlight>


Alternatively, using the ''reduce{}'' method:
Alternatively, using the ''reduce{}'' method:
<lang ruby>say (1..1000 -> reduce { |a,b| a + (1 / b**2) })</lang>
<syntaxhighlight lang="ruby">say (1..1000 -> reduce { |a,b| a + (1 / b**2) })</syntaxhighlight>


{{out}}
{{out}}
Line 2,744: Line 2,744:
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:


<lang slate>((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).</lang>
<syntaxhighlight lang="slate">((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>( (1 to: 1000) fold: [:sum :aNumber |
<syntaxhighlight lang="smalltalk">( (1 to: 1000) fold: [:sum :aNumber |
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.</lang>
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.</syntaxhighlight>


=={{header|SQL}}==
=={{header|SQL}}==
<lang SQL>create table t1 (n real);
<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,757: Line 2,757:
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,767: Line 2,767:


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>function series(n) {
<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</lang>
-.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,787: Line 2,787:


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,812: Line 2,812:


y = 1000.sumSeries()
y = 1000.sumSeries()
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 2,818: Line 2,818:
=== Using Expansion Operator and mathop ===
=== Using Expansion Operator and mathop ===
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>package require 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</lang>
lsum_series [range 1 1001] ;# ==> 1.6439345666815615</syntaxhighlight>


=== Using Loop ===
=== Using Loop ===
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>package require 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,838: Line 2,838:
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</lang>
partial_sum $S from 1 to 1000 ;# => 1.6439345666815615</syntaxhighlight>


=== Using tcllib ===
=== Using tcllib ===
{{tcllib|struct::list}}
{{tcllib|struct::list}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
package require struct::list


Line 2,851: Line 2,851:
set S {x {expr {1.0 / $x**2}}}
set S {x {expr {1.0 / $x**2}}}


sum_of $S [range 1 1001] ;# ==> 1.6439345666815615</lang>
sum_of $S [range 1 1001] ;# ==> 1.6439345666815615</syntaxhighlight>


The helper <code>range</code> procedure is:
The helper <code>range</code> procedure is:
<lang tcl># a range command akin to Python's
<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,869: Line 2,869:
}
}
return $range
return $range
}</lang>
}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 2,875: Line 2,875:
{{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}}
<lang ti83b>
<syntaxhighlight lang="ti83b">
∑(1/X²,X,1,1000)
∑(1/X²,X,1,1000)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,886: Line 2,886:


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.
<lang ti83b>sum(seq(1/X²,X,1,999))</lang>
<syntaxhighlight lang="ti83b">sum(seq(1/X²,X,1,999))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,894: Line 2,894:
=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<lang ti89b>∑(1/x^2,x,1,1000)</lang>
<syntaxhighlight lang="ti89b">∑(1/x^2,x,1,1000)</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 2,902: Line 2,902:
Variant A1: limit the list generation inside the <code>gen</code> operator.
Variant A1: limit the list generation inside the <code>gen</code> operator.


<lang txr>txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]'
<syntaxhighlight lang="txr">txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]'
1.64393456668156</lang>
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>.


<lang txr>txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]'
<syntaxhighlight lang="txr">txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]'
1.64393456668156</lang>
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.


<lang txr>txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]'
<syntaxhighlight lang="txr">txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]'
1.64393456668156</lang>
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.


<lang txr>txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]'
<syntaxhighlight lang="txr">txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]'
1.64393456668156</lang>
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.


<lang txr>txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]'
<syntaxhighlight lang="txr">txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]'
1.64393456668156</lang>
1.64393456668156</syntaxhighlight>


=={{header|Unicon}}==
=={{header|Unicon}}==
Line 2,929: Line 2,929:


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
<lang bash>term() {
<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,946: Line 2,946:
}
}


(echo 3; echo 1; echo 4) | fold sum</lang>
(echo 3; echo 1; echo 4) | fold sum</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 2,954: Line 2,954:
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.
<lang Ursala>#import flo
<syntaxhighlight lang="ursala">#import flo
#import nat
#import nat


#cast %e
#cast %e


total = plus:-0 div/*1. sqr* float*t iota 1001</lang>
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}}==
<lang 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,974: Line 2,974:
stdout.printf("%s\n", sum.to_string());
stdout.printf("%s\n", sum.to_string());
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,982: Line 2,982:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Function sumto(n As Integer) As Double
<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,991: Line 2,991:
Public Sub main()
Public Sub main()
Debug.Print sumto(1000)
Debug.Print sumto(1000)
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 1,64393456668156 </pre>
<pre> 1,64393456668156 </pre>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>' Sum of a series
<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 </lang>
wscript.echo s </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,008: Line 3,008:
{{trans|VBScript}}
{{trans|VBScript}}
{{works with|Visual Basic .NET|2013}}
{{works with|Visual Basic .NET|2013}}
<lang vbnet>' Sum of a series
<syntaxhighlight lang="vbnet">' Sum of a series
Sub SumOfaSeries()
Sub SumOfaSeries()
Dim s As Double
Dim s As Double
Line 3,016: Line 3,016:
Next 'i
Next 'i
Console.WriteLine(s)
Console.WriteLine(s)
End Sub </lang>
End Sub </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,024: Line 3,024:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}
<lang vlang>import math
<syntaxhighlight lang="vlang">import math


fn main(){
fn main(){
Line 3,033: Line 3,033:
}
}
println('computed: $sum')
println('computed: $sum')
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>known: 1.6449340668482264
<pre>known: 1.6449340668482264
Line 3,039: Line 3,039:


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let s => import 'stream';
<syntaxhighlight lang="wdte">let s => import 'stream';


s.range 1 1001
s.range 1 1001
Line 3,045: Line 3,045:
-> s.reduce 0 +
-> s.reduce 0 +
-- io.writeln io.stdout
-- io.writeln io.stdout
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 3,051: Line 3,051:


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@sum !*#~V1Sn @to 1000 ; returns 1.6439345666815615</lang>
<syntaxhighlight lang="wortel">@sum !*#~V1Sn @to 1000 ; returns 1.6439345666815615</syntaxhighlight>
<lang wortel>@to 1000 ; generates a list of 1 to 1000 (inclusive)
<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</lang>
@sum ; sums the list</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var sumSeries = Fn.new { |n| (1..n).reduce(0) { |sum, i| sum + 1/(i*i) } }
<syntaxhighlight lang="ecmascript">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)")</lang>
System.print("zeta(2) = %(Num.pi*Num.pi/6)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,070: Line 3,070:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code CrLf=9; code real RlOut=48;
<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);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 3,083: Line 3,083:


=={{header|Yorick}}==
=={{header|Yorick}}==
<lang yorick>(1./indgen(1:1000)^2)(sum)</lang>
<syntaxhighlight lang="yorick">(1./indgen(1:1000)^2)(sum)</syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


fn f(x: i64) f64 {
fn f(x: i64) f64 {
Line 3,106: Line 3,106:
const stdout = std.io.getStdOut().writer();
const stdout = std.io.getStdOut().writer();
try stdout.print("S_1000 = {d:.15}\n", .{S(f, 1000)});
try stdout.print("S_1000 = {d:.15}\n", .{S(f, 1000)});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>S_1000 = 1.643934566681560</pre>
<pre>S_1000 = 1.643934566681560</pre>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>[1.0..1000].reduce(fcn(p,n){ p + 1.0/(n*n) },0.0) //-->1.64394</lang>
<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}}==
<lang zxbasic>10 LET n=1000
<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</lang>
60 PRINT s</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>