Sum of a series: Difference between revisions

(Added solution for Action!)
 
(33 intermediate revisions by 22 users not shown)
Line 21:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">print(sum((1..1000).map(x -> 1.0/x^2)))</langsyntaxhighlight>
 
{{out}}
Line 29:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Sum of a series 30/03/2017
SUMSER CSECT
USING SUMSER,12 base register
Line 52:
COPY FORMATF formatf code
PG DC CL80' ' buffer
END SUMSER</langsyntaxhighlight>
{{out}}
<pre>
Line 59:
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">(defun sum-x^-2 (max-x)
(if (zp max-x)
0
(+ (/ (* max-x max-x))
(sum-x^-2 (1- max-x)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC Calc(CARD n REAL POINTER res)
Line 102:
PrintF("s(%U)=",n)
PrintRE(res)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_a_series.png Screenshot from Atari 8-bit computer]
Line 110:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function partialSum(n:uint):Number
{
var sum:Number = 0;
Line 117:
return sum;
}
trace(partialSum(1000));</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Sum_Series is
Line 139:
Put(Item => Sum, Aft => 10, Exp => 0);
New_Line;
end Sum_Series;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">real
Invsqr(real n)
{
Line 166:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">MODE RANGE = STRUCT(INT lwb, upb);
 
PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:(
Line 183:
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))
)</langsyntaxhighlight>
Output:
<pre>
Line 191:
=={{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.
<langsyntaxhighlight lang="algolw">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 %
Line 206:
end;
write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) )
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 213:
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl"> +/÷2*⍨⍳1000
1.64393</langsyntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">----------------------- SUM OF SERIES ----------------------
 
-- seriesSum :: Num a => (a -> a) -> [a] -> a
Line 287:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang AppleScript="applescript">1.643934566682</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">series: map 1..1000 => [1.0/&^2]
print [sum series]</langsyntaxhighlight>
 
{{out}}
 
<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}}==
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.
<langsyntaxhighlight lang="autohotkey">SetFormat, FloatFast, 0.15
While A_Index <= 1000
sum += 1/A_Index**2
MsgBox,% sum ;1.643934566681554</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}'
1.64393</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic">function s(x%)
s = 1 / x ^ 2
end function
Line 323 ⟶ 330:
sum = ret
end function
print sum(1, 1000)</langsyntaxhighlight>
 
==={{header|BASIC256}}===
{{works with|True BASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
function sumSeries(n)
if n = 0 then sumSeries = 0
Line 340 ⟶ 347:
print "zeta(2) = "; pi * pi / 6
end
</syntaxhighlight>
</lang>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> FOR i% = 1 TO 1000
sum += 1/i%^2
NEXT
PRINT sum</langsyntaxhighlight>
 
==={{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}}
<langsyntaxhighlight lang="qbasic">
FUNCTION sumSeries(n)
IF n = 0 then
Line 365 ⟶ 407:
PRINT "zeta(2) = "; pi * pi / 6
END
</syntaxhighlight>
</lang>
 
==={{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}}===
<langsyntaxhighlight lang="yabasic">
sub sumSeries(n)
if n = 0 then return 0 : fi
Line 381 ⟶ 450:
print "zeta(2) = ", pi * pi / 6
end
</syntaxhighlight>
</lang>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">define f(x) {
return(1 / (x * x))
}
Line 399 ⟶ 468:
 
scale = 20
s(1000)</langsyntaxhighlight>
 
{{Out}}
Line 405 ⟶ 474:
 
=={{header|Beads}}==
<langsyntaxhighlight Beadslang="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)</langsyntaxhighlight>
{{out}}
<pre>1.6439345666815615</pre>
Line 416 ⟶ 485:
=={{header|Befunge}}==
Emulates fixed point arithmetic with a 32 bit integer so the result is not very accurate.
<langsyntaxhighlight lang="befunge">05558***>::"~"%00p"~"/10p"( }}2"*v
v*8555$_^#!:-1+*"~"g01g00+/*:\***<
<@$_,#!>#:<+*<v+*86%+55:p00<6\0/**
"."\55+%68^>\55+/00g1-:#^_$</langsyntaxhighlight>
{{out}}
<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}}==
<langsyntaxhighlight lang="bracmat">( 0:?i
& 0:?S
& whl'(1+!i:~>1000:?i&!i^-2+!S:?S)
& out$!S
& out$(flt$(!S,10))
);</langsyntaxhighlight>
Output:
<pre>8354593848314...../5082072010432..... (1732 digits and a slash)
Line 435 ⟶ 511:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
double Invsqr(double n)
Line 456 ⟶ 532:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">class Program
{
static void Main(string[] args)
Line 477 ⟶ 553:
Console.ReadLine();
}
}</langsyntaxhighlight>
 
An alternative approach using Enumerable.Range() to generate the numbers.
 
<langsyntaxhighlight lang="csharp">class Program
{
static void Main(string[] args)
Line 490 ⟶ 566:
Console.ReadLine();
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
double f(double x);
Line 515 ⟶ 591:
{
return ( 1.0 / ( x * x ) );
}</langsyntaxhighlight>
 
=={{header|CLIPS}}==
<langsyntaxhighlight lang="clips">(deffunction S (?x) (/ 1 (* ?x ?x)))
(deffunction partial-sum-S
(?start ?stop)
Line 526 ⟶ 602:
)
(return ?sum)
)</langsyntaxhighlight>
 
Usage:
Line 533 ⟶ 609:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(reduce + (map #(/ 1.0 % %) (range 1 1001)))</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. sum-of-series.
 
Line 554 ⟶ 653:
 
GOBACK
.</langsyntaxhighlight>
{{out}}
<pre>
Line 561 ⟶ 660:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
<lang CoffeeScript>
console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x)))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(loop for x from 1 to 1000 summing (expt x -2))</langsyntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">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</langsyntaxhighlight>
{{out}}
<pre>
Line 584 ⟶ 683:
=={{header|D}}==
===More Procedural Style===
<langsyntaxhighlight lang="d">import std.stdio, std.traits;
 
ReturnType!TF series(TF)(TF func, int end, int start=1)
Line 596 ⟶ 695:
void main() {
writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000));
}</langsyntaxhighlight>
{{out}}
<pre>Sum: 1.64393</pre>
Line 602 ⟶ 701:
===More functional Style===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
enum series(alias F) = (in int end, in int start=1)
Line 609 ⟶ 708:
void main() {
writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000));
}</langsyntaxhighlight>
 
=={{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}}==
{{trans|Scala}}
<langsyntaxhighlight lang="dart">main() {
var list = new List<int>.generate(1000, (i) => i + 1);
 
Line 622 ⟶ 726:
});
print(sum);
}</langsyntaxhighlight>
 
{{trans|F#}}
<langsyntaxhighlight lang="dart">f(double x) {
if (x == 0)
return x;
Line 634 ⟶ 738:
main() {
print(f(1000));
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Form_SumOfASeries_Unit;
 
Line 685 ⟶ 789:
end.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>1.64393456668156</pre>
Line 691 ⟶ 795:
=={{header|DWScript}}==
 
<langsyntaxhighlight lang="delphi">
var s : Float;
for var i := 1 to 1000 do
Line 697 ⟶ 801:
 
PrintLn(s);
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
Line 703 ⟶ 807:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func Integer.sumSeriesSumSeries() {
var ret = 0
 
Line 714 ⟶ 818:
var x = 1000
print(x.sumSeriesSumSeries())</langsyntaxhighlight>
 
{{out}}
Line 722 ⟶ 826:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
numfmt 8 0
for i = 1 to 1000
s += 1 / (i * i)
.
print s
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(lib 'math) ;; for (sigma f(n) nfrom nto) function
(Σ (λ(n) (// (* n n))) 1 1000)
Line 735 ⟶ 848:
(// (* PI PI) 6)
→ 1.6449340668482264
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Line 741 ⟶ 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.
<langsyntaxhighlight lang="edsac">
[Sum of a series, Rosetta Code website.
EDSAC program, Initial Orders 2.]
Line 804 ⟶ 917:
[89] O5@ ZF [flush teleprinter buffer; stop]
E15Z PF [define entry point; enter with acc = 0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 812 ⟶ 925:
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
note
description: "Compute the n-th term of a series"
Line 864 ⟶ 977:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">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)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 883 ⟶ 996:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end)
1.6439345666815615</langsyntaxhighlight>
 
=={{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>
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>
 
=={{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}}==
 
<langsyntaxhighlight lang="erlang">lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]).</langsyntaxhighlight>
 
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
This is based on the [[BASIC]] example.
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function s( atom x )
return 1 / power( x, 2 )
Line 920 ⟶ 1,087:
end function
 
printf( 1, "%.15f\n", sum( 1, 1000 ) )</langsyntaxhighlight>
 
=={{header|Excel}}==
Line 932 ⟶ 1,099:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">sumOfSeries
=LAMBDA(f,
LAMBDA(n,
Line 945 ⟶ 1,112:
=LAMBDA(n,
1 / (n ^ 2)
)</langsyntaxhighlight>
 
{{Out}}
Line 979 ⟶ 1,146:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது
 
Line 1,005 ⟶ 1,172:
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
The following function will do the task specified.
<langsyntaxhighlight lang="fsharp">let rec f (x : float) =
match x with
| 0. -> x
| x -> (1. / (x * x)) + f (x - 1.)</langsyntaxhighlight>
In the interactive F# console, using the above gives:
<langsyntaxhighlight lang="fsharp">> f 1000. ;;
val it : float = 1.643934567</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="fsharp">#light
let sum_series (max : float) =
let rec f (a:float, x : float) =
Line 1,029 ⟶ 1,196:
let (b, max) = System.Double.TryParse(args.[0])
printfn "%A" (sum_series max)
0</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="fsharp">
Seq.sum [for x in [1..1000] do 1./(x * x |> float)]
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">1000 [1,b] [ >float sq recip ] map-sum</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 1,044 ⟶ 1,211:
Within 'fansh':
 
<langsyntaxhighlight lang="fantom">
fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) }
1.6439345666815615
</syntaxhighlight>
</lang>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">Sigma<k=1,1000>[1/k^2]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,071 ⟶ 1,238:
 
=={{header|Fish}}==
<langsyntaxhighlight lang="fish">0&aaa**>::*1$,&v
;n&^?:-1&+ <</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: sum ( fn start count -- fsum )
0e
bounds do
Line 1,083 ⟶ 1,250:
:noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt )
1 1000 sum f. \ 1.64393456668156
pi pi f* 6e f/ f. \ 1.64493406684823</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 and later, use SUM intrinsic:
<langsyntaxhighlight lang="fortran">real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /)
real :: result
 
result = sum(a);</langsyntaxhighlight>
Or in Fortran 77:
<langsyntaxhighlight lang="fortran"> s=0
do i=1,1000
s=s+1./i**2
end do
write (*,*) s
end</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const pi As Double = 3.141592653589793
Line 1,117 ⟶ 1,284:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,127 ⟶ 1,294:
=={{header|Frink}}==
Frink can calculate the series with exact rational numbers or floating-point values.
<langsyntaxhighlight lang="frink">
sum[map[{|k| 1/k^2}, 1 to 1000]]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,138 ⟶ 1,305:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_of_a_series}}
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 &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
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
In '''[https://formulae.org/?example=Sum_of_a_series this]''' page you can see the program(s) related to this task and their results.
 
[[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]]
 
[[File:Fōrmulæ - Sum of a series 07.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># We will compute the sum exactly
 
# Computing an approximation of a rationnal (giving a string)
Line 1,176 ⟶ 1,367:
Approx(a, 10);
"1.6439345666"
# and pi^2/6 is 1.6449340668, truncated to ten digits</langsyntaxhighlight>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Sum of series, in Genie
Line 1,200 ⟶ 1,391:
Intl.setlocale()
print "ζ(2) approximation: %16.15f", sum_series(1, 1000, oneOverSquare)
print "π² / 6 : %16.15f", Math.PI * Math.PI / 6.0</langsyntaxhighlight>
 
{{out}}
Line 1,209 ⟶ 1,400:
 
=={{header|GEORGE}}==
<syntaxhighlight lang="george">
<lang GEORGE>
0 (s)
1, 1000 rep (i)
Line 1,215 ⟶ 1,406:
]
P
</syntaxhighlight>
</lang>
Output:-
<pre>
Line 1,222 ⟶ 1,413:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import ("fmt"; "math")
Line 1,233 ⟶ 1,424:
}
fmt.Println("computed:", sum)
}</langsyntaxhighlight>
Output:
<pre>known: 1.6449340668482264
Line 1,240 ⟶ 1,431:
=={{header|Groovy}}==
Start with smallest terms first to minimize rounding error:
<langsyntaxhighlight lang="groovy">println ((1000..1).collect { x -> 1/(x*x) }.sum())</langsyntaxhighlight>
 
Output:
Line 1,247 ⟶ 1,438:
=={{header|Haskell}}==
With a list comprehension:
<langsyntaxhighlight lang="haskell">sum [1 / x ^ 2 | x <- [1..1000]]</langsyntaxhighlight>
With higher-order functions:
<langsyntaxhighlight lang="haskell">sum $ map (\x -> 1 / x ^ 2) [1..1000]</langsyntaxhighlight>
In [http://haskell.org/haskellwiki/Pointfree point-free] style:
<langsyntaxhighlight lang="haskell">(sum . map (1/) . map (^2)) [1..1000]</langsyntaxhighlight>
or
<langsyntaxhighlight lang="haskell">(sum . map ((1 /) . (^ 2))) [1 .. 1000]</langsyntaxhighlight>
 
or, as a single fold:
 
<langsyntaxhighlight lang="haskell">seriesSum f = foldr ((+) . f) 0
 
inverseSquare = (1 /) . (^ 2)
 
main :: IO ()
main = print $ seriesSum inverseSquare [1 .. 1000]</langsyntaxhighlight>
{{Out}}
<pre>1.6439345666815615</pre>
Line 1,268 ⟶ 1,459:
=={{header|Haxe}}==
===Procedural===
<langsyntaxhighlight lang="haxe">using StringTools;
 
class Main {
Line 1,278 ⟶ 1,469:
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,287 ⟶ 1,478:
 
===Functional===
<langsyntaxhighlight lang="haxe">using Lambda;
using StringTools;
 
Line 1,296 ⟶ 1,487:
Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,302 ⟶ 1,493:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: a(1000)
a = 1 / $^2
WRITE(ClipBoard, Format='F17.15') SUM(a) </langsyntaxhighlight>
<syntaxhighlight lang ="hicest">1.643934566681561</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main()
local i, sum
sum := 0 & i := 0
every sum +:= 1.0/((| i +:= 1 ) ^ 2) \1000
write(sum)
end</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="icon">procedure main()
every (sum := 0) +:= 1.0/((1 to 1000)^2)
write(sum)
end</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="icon">
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
(sum := 0) # returns a reference to sum which can in turn be used with augmented assignment +:=
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">print,total( 1/(1+findgen(1000))^2)</langsyntaxhighlight>
 
=={{header|Io}}==
Line 1,343 ⟶ 1,534:
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> NB. sum of reciprocals of squares of first thousand positive integers
+/ % *: >: i. 1000
1.64393
Line 1,351 ⟶ 1,542:
1r6p2 NB. As a constant (J has a rich constant notation)
1.64493</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Sum{
public static double f(double x){
return 1/(x*x);
Line 1,368 ⟶ 1,559:
System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function sum(a,b,fn) {
var s = 0;
for ( ; a <= b; a++) s += fn(a);
Line 1,378 ⟶ 1,569:
}
sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156</langsyntaxhighlight>
 
or, in a functional idiom:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
function sum(fn, lstRange) {
Line 1,406 ⟶ 1,597:
);
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang JavaScript="javascript">1.6439345666815615</langsyntaxhighlight>
 
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,438 ⟶ 1,629:
 
return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000));
})();</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang JavaScript="javascript">1.6439345666815615</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">1000 [0] [swap -2 pow +] primrec.</syntaxhighlight>
{{out}}
<pre>1.64393</pre>
 
=={{header|jq}}==
Line 1,446 ⟶ 1,642:
 
Directly:
<langsyntaxhighlight lang="jq">def s(n): reduce range(1; n+1) as $k (0; . + 1/($k * $k) );
 
s(1000)
</syntaxhighlight>
</lang>
{{Out}}
1.6439345666815615
Line 1,455 ⟶ 1,651:
Using a generic summation wrapper function allows problems specified in "sigma" notation to be solved using syntax that closely resembles that notation:
 
<langsyntaxhighlight lang="jq">def summation(s): reduce s as $k (0; . + $k);
 
summation( range(1; 1001) | (1/(. * .) ) )</langsyntaxhighlight>
 
An important point is that nothing is lost in efficiency using the declarative and quite elegant approach using "summation".
Line 1,464 ⟶ 1,660:
From Javascript ES5.
 
<langsyntaxhighlight lang="javascript">#!/usr/bin/jsish
/* Sum of a series */
function sum(a:number, b:number , fn:function):number {
Line 1,478 ⟶ 1,674:
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,487 ⟶ 1,683:
Using a higher-order function:
 
<langsyntaxhighlight Julialang="julia">julia> sum(k -> 1/k^2, 1:1000)
1.643934566681559
 
julia> pi^2/6
1.6449340668482264
</syntaxhighlight>
</lang>
 
A simple loop is more optimized:
 
<langsyntaxhighlight Julialang="julia">julia> function f(n)
s = 0.0
for k = 1:n
Line 1,505 ⟶ 1,701:
 
julia> f(1000)
1.6439345666815615</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> ssr: +/1%_sqr
ssr 1+!1000
1.643935</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 1,520 ⟶ 1,716:
println("Actual sum is $sum")
println("zeta(2) is ${Math.PI * Math.PI / 6.0}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,529 ⟶ 1,725:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="lisp">
{+ {S.map {lambda {:k} {/ 1 {* :k :k}}} {S.serie 1 1000}}}
-> 1.6439345666815615 ~ 1.6449340668482264 = PI^2/6
</syntaxhighlight>
</lang>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">1000 iota 1 + 1 swap / 2 ** '+ reduce .</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight Lassolang="lasso">define sum_of_a_series(n::integer,k::integer) => {
local(sum = 0)
loop(-from=#k,-to=#n) => {
Line 1,545 ⟶ 1,762:
return #sum
}
sum_of_a_series(1000,1)</langsyntaxhighlight>
{{out}}
<pre>1.643935</pre>
Line 1,553 ⟶ 1,770:
=== With <code>lists:foldl</code> ===
 
<langsyntaxhighlight lang="lisp">
(defun sum-series (nums)
(lists:foldl
Line 1,561 ⟶ 1,778:
(lambda (x) (/ 1 x x))
nums)))
</syntaxhighlight>
</lang>
 
=== With <code>lists:sum</code> ===
 
<langsyntaxhighlight lang="lisp">
(defun sum-series (nums)
(lists:sum
Line 1,571 ⟶ 1,788:
(lambda (x) (/ 1 x x))
nums)))
</syntaxhighlight>
</lang>
 
Both have the same result:
 
<langsyntaxhighlight lang="lisp">
> (sum-series (lists:seq 1 100000))
1.6449240668982423
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for i =1 to 1000
sum =sum +1 /( i^2)
Line 1,589 ⟶ 1,806:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">the floatprecision = 8
sum = 0
repeat with i = 1 to 1000
Line 1,598 ⟶ 1,815:
end repeat
put sum
-- 1.64393457</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">repeat with i = 1 to 1000
add 1/(i^2) to summ
end repeat
put summ //1.643935</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to series :fn :a :b
localmake "sigma 0
for [i :a :b] [make "sigma :sigma + invoke :fn :i]
Line 1,617 ⟶ 1,834:
print series "zeta.2 1 1000
make "pi (radarctan 0 1) * 2
print :pi * :pi / 6</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
sum = 0
for i = 1, 1000 do sum = sum + 1/i^2 end
print(sum)
</syntaxhighlight>
</lang>
 
=={{header|Lucid}}==
<langsyntaxhighlight lang="lucid">series = ssum asa n >= 1000
where
num = 1 fby num + 1;
ssum = ssum + 1/(num * num)
end;</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">sum(1/k^2, k=1..1000);</langsyntaxhighlight>
{{Out|Output}}
<pre>-Psi(1, 1001)+(1/6)*Pi^2</pre>
Line 1,640 ⟶ 1,857:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This is the straightforward solution of the task:
<langsyntaxhighlight lang="mathematica">Sum[1/x^2, {x, 1, 1000}]</langsyntaxhighlight>
However this returns a quotient of two huge integers (namely the ''exact'' sum); to get a floating point approximation, use <tt>N</tt>:
<langsyntaxhighlight lang="mathematica">N[Sum[1/x^2, {x, 1, 1000}]]</langsyntaxhighlight>
or better:
<langsyntaxhighlight lang="mathematica">NSum[1/x^2, {x, 1, 1000}]</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="mathematica">Sum[1./x^2, {x, 1, 1000}]</langsyntaxhighlight>
Other ways include (exact, approximate,exact,approximate):
<langsyntaxhighlight lang="mathematica">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}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang="matlab"> sum([1:1000].^(-2)) </langsyntaxhighlight>
 
=={{header|Maxima}}==
 
<langsyntaxhighlight lang="maxima">(%i45) sum(1/x^2, x, 1, 1000);
835459384831496894781878542648[806 digits]396236858699094240207812766449
(%o45) ------------------------------------------------------------------------
Line 1,664 ⟶ 1,881:
 
(%i46) sum(1/x^2, x, 1, 1000),numer;
(%o46) 1.643934566681561</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">total = 0
for i in 1 to 1000 do
(
total += 1.0 / pow i 2
)
print total</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">0 1 (
((dup * 1 swap /) (id)) cleave
((+) (succ)) spread
) 1000 times pop print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,686 ⟶ 1,903:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">zeta = function(num)
return 1 / num^2
end function
Line 1,699 ⟶ 1,916:
 
print sum(1, 1000, @zeta)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,706 ⟶ 1,923:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">0 П0 П1 ИП1 1 + П1 x^2 1/x ИП0
+ П0 ИП1 1 0 0 0 - x>=0 03
ИП0 С/П</langsyntaxhighlight>
 
=={{header|ML}}==
 
==={{header|Standard ML}}===
<syntaxhighlight lang="standard ml">
<lang Standard ML>
(* 1.64393456668 *)
List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0)))
</syntaxhighlight>
</lang>
 
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">println ` fold (+, 0) ` map (fn x = 1 / x ^ 2) ` iota (1,1000);</langsyntaxhighlight>
Output:
<pre>1.6439345666815549</pre>
 
=={{header|MMIX}}==
<langsyntaxhighlight lang="mmix">x IS $1 % flt calculations
y IS $2 % id
z IS $3 % z = sum series
Line 1,829 ⟶ 2,046:
PBNP t,1B } z = sum
GO $127,prtFlt print sum --> StdOut
TRAP 0,Halt,0</langsyntaxhighlight>
Output:
<pre>~/MIX/MMIX/Rosetta> mmix sumseries
Line 1,835 ⟶ 2,052:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE SeriesSum;
FROM InOut IMPORT WriteLn;
FROM RealInOut IMPORT WriteReal;
Line 1,860 ⟶ 2,077:
WriteReal(seriesSum(1, 1000, oneOverKSquared), 10);
WriteLn;
END SeriesSum.</langsyntaxhighlight>
{{out}}
<pre>1.6439E+00</pre>
Line 1,866 ⟶ 2,083:
=={{header|Modula-3}}==
Modula-3 uses D0 after a floating point number as a literal for <tt>LONGREAL</tt>.
<langsyntaxhighlight lang="modula3">MODULE Sum EXPORTS Main;
 
IMPORT IO, Fmt, Math;
Line 1,884 ⟶ 2,101:
IO.Put(Fmt.LongReal(sum));
IO.Put("\n");
END Sum.</langsyntaxhighlight>
Output:
<pre>
Line 1,891 ⟶ 2,108:
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
<lang MUMPS>
SOAS(N)
NEW SUM,I SET SUM=0
Line 1,897 ⟶ 2,114:
.SET SUM=SUM+(1/((I*I)))
QUIT SUM
</syntaxhighlight>
</lang>
This is an extrinsic function so the usage is:
<pre>
Line 1,905 ⟶ 2,122:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(let (s 0)
(for (i 1 1000)
(inc s (div 1 (* i i))))
(println s))</langsyntaxhighlight>
 
=={{header|Nial}}==
<langsyntaxhighlight lang="nial">|sum (1 / power (count 1000) 2)
=1.64393</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var s = 0.0
for n in 1..1000: s += 1 / (n * n)
echo s</langsyntaxhighlight>
 
{{out}}
<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}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class SumSeries {
Line 1,948 ⟶ 2,198:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sum a b fn =
let result = ref 0. in
for i = a to b do
result := !result +. fn i
done;
!result</langsyntaxhighlight>
 
# sum 1 1000 (fun x -> 1. /. (float x ** 2.))
Line 1,962 ⟶ 2,212:
 
or in a functional programming style:
<langsyntaxhighlight lang="ocaml">let sum a b fn =
let rec aux i r =
if i > b then r
Line 1,968 ⟶ 2,218:
in
aux a 0.
;;</langsyntaxhighlight>
Simple recursive solution:
<langsyntaxhighlight lang="ocaml">let rec sum n = if n < 1 then 0.0 else sum (n-1) +. 1.0 /. float (n*n)
in sum 1000</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="octave">sum(1 ./ [1:1000] .^ 2)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: sumSerie(s, n) 0 n seq apply(#[ s perform + ]) ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth"> #[ sq inv ] 1000 sumSerie println</langsyntaxhighlight>
 
{{out}}
Line 1,994 ⟶ 2,244:
Conventionally like elsewhere:
 
<langsyntaxhighlight Progresslang="progress (Openedgeopenedge ABLabl)">def var dcResult as decimal no-undo.
def var n as int no-undo.
 
Line 2,001 ⟶ 2,251:
end.
 
display dcResult .</langsyntaxhighlight>
 
or like this:
 
<langsyntaxhighlight Progresslang="progress (Openedgeopenedge ABLabl)">def var n as int no-undo.
 
repeat n = 1 to 1000 :
Line 2,011 ⟶ 2,261:
end.
 
display ( accum total 1 / (n * n) ) .</langsyntaxhighlight>
 
=={{header|Oz}}==
With higher-order functions:
<langsyntaxhighlight lang="oz">declare
fun {SumSeries S N}
{FoldL {Map {List.number 1 N 1} S}
Line 2,025 ⟶ 2,275:
end
in
{Show {SumSeries S 1000}}</langsyntaxhighlight>
 
Iterative:
<langsyntaxhighlight lang="oz"> fun {SumSeries S N}
R = {NewCell 0.}
in
Line 2,035 ⟶ 2,285:
end
@R
end</langsyntaxhighlight>
 
=={{header|Panda}}==
<langsyntaxhighlight lang="panda">sum{{1.0.divide(1..1000.sqr)}}</langsyntaxhighlight>
Output:
<pre>1.6439345666815615</pre>
Line 2,044 ⟶ 2,294:
=={{header|PARI/GP}}==
Exact rational solution:
<langsyntaxhighlight lang="parigp">sum(n=1,1000,1/n^2)</langsyntaxhighlight>
 
Real number solution (accurate to <math>3\cdot10^{-36}</math> at standard precision):
<langsyntaxhighlight lang="parigp">sum(n=1,1000,1./n^2)</langsyntaxhighlight>
 
Approximate solution (accurate to <math>9\cdot10^{-11}</math> at standard precision):
<langsyntaxhighlight lang="parigp">zeta(2)-intnum(x=1000.5,[1],1/x^2)</langsyntaxhighlight>
or
<syntaxhighlight lang ="parigp">zeta(2)-1/1000.5</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program SumSeries;
type
tOutput = double;//extended;
Line 2,078 ⟶ 2,328:
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.</langsyntaxhighlight>
Output
<pre>different version of type and calculation
Line 2,091 ⟶ 2,341:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $sum = 0;
$sum += 1 / $_ ** 2 foreach 1..1000;
print "$sum\n";</langsyntaxhighlight>
or
<langsyntaxhighlight lang="perl">use List::Util qw(reduce);
$sum = reduce { $a + 1 / $b ** 2 } 0, 1..1000;
print "$sum\n";</langsyntaxhighlight>
An other way of doing it is to define the series as a closure:
<langsyntaxhighlight lang="perl">my $S = do { my ($sum, $k); sub { $sum += 1/++$k**2 } };
my @S = map &$S, 1 .. 1000;
print $S[-1];</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 2,113 ⟶ 2,363:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,120 ⟶ 2,370:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
 
/**
Line 2,142 ⟶ 2,392:
 
echo sum_of_a_series(1000,1);
</syntaxhighlight>
</lang>
{{out}}
<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}}==
<langsyntaxhighlight PicoLisplang="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</langsyntaxhighlight>
Output:
<pre>1.643935</pre>
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">array(int) x = enumerate(1000,1,1);
`+(@(1.0/pow(x[*],2)[*]));
Result: 1.64393</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* sum the first 1000 terms of the series 1/n**2. */
s = 0;
 
Line 2,169 ⟶ 2,474:
end;
 
put skip list (s);</langsyntaxhighlight>
 
{{out}}
Line 2,178 ⟶ 2,483:
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">lvars s = 0, j;
for j from 1 to 1000 do
s + 1.0/(j*j) -> s;
endfor;
 
s =></langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/aproxriemann{
/x exch def
Line 2,199 ⟶ 2,504:
 
1000 aproxriemann
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="text">
1.64393485
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
% using map
[1 1000] 1 range {dup * 1 exch div} map 0 {+} fold
Line 2,212 ⟶ 2,517:
% just using fold
[1 1000] 1 range 0 {dup * 1 exch div +} fold
</syntaxhighlight>
</lang>
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">sum = 0.0
1 to 1000 (i): sum = sum + 1.0 / (i * i).
sum print</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$x = 1..1000 `
| ForEach-Object { 1 / ($_ * $_) } `
| Measure-Object -Sum
Write-Host Sum = $x.Sum</langsyntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">sum(S) :-
findall(L, (between(1,1000,N),L is 1/N^2), Ls),
sumlist(Ls, S).
</syntaxhighlight>
</lang>
Ouptput :
<pre>?- sum(S).
Line 2,237 ⟶ 2,542:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Define i, sum.d
 
For i=1 To 1000
Line 2,243 ⟶ 2,548:
Next i
 
Debug sum</langsyntaxhighlight>
<tt>
Answer = 1.6439345666815615
Line 2,249 ⟶ 2,554:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">print ( sum(1.0 / (x * x) for x in range(1, 1001)) )</langsyntaxhighlight>
Or, as a generalised map, or fold / reduction – (see [[Catamorphism#Python]]):
<langsyntaxhighlight lang="python">'''The sum of a series'''
 
from functools import reduce
Line 2,324 ⟶ 2,629:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>The sum of a series:
Line 2,332 ⟶ 2,637:
 
=={{header|Q}}==
<langsyntaxhighlight lang="q">sn:{sum xexp[;-2] 1+til x}
sn 1000</langsyntaxhighlight>
 
{{Out}}
Line 2,342 ⟶ 2,647:
Using the Quackery bignum rational arithmetic suite <code>bigrat.qky</code>.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ 0 n->v rot times
Line 2,359 ⟶ 2,664:
say "As a decimal fraction, first 1000 places after the decimal point."
cr cr
1000 point$ echo$</langsyntaxhighlight>
 
{{out}}
Line 2,374 ⟶ 2,679:
 
=={{header|R}}==
<langsyntaxhighlight lang="r">print( sum( 1/seq(1000)^2 ) )</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,380 ⟶ 2,685:
A solution using Typed Racket:
 
<langsyntaxhighlight lang="racket">
#lang typed/racket
 
Line 2,387 ⟶ 2,692:
(for/sum: : Real ([k : Natural (in-range 1 (+ n 1))])
(/ 1.0 (* k k))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,395 ⟶ 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
 
<syntaxhighlight lang="raku" perl6line>[+] map &f, 1 .. $n</langsyntaxhighlight>
 
So what's needed in this case is
 
<syntaxhighlight lang="raku" perl6line>say [+] map { 1 / $^n**2 }, 1 .. 1000;</langsyntaxhighlight>
 
Or, using the "hyper" metaoperator to vectorize, we can use a more "point free" style while keeping traditional precedence:
<syntaxhighlight lang="raku" perl6line>say [+] 1 «/« (1..1000) »**» 2;</langsyntaxhighlight>
 
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:
 
<syntaxhighlight lang="raku" perl6line>say [+] 1 X/ (1..1000 X** 2);</langsyntaxhighlight>
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:
 
<syntaxhighlight lang="raku" perl6line>say [+] (1 / $_**2 for 1..1000);</langsyntaxhighlight>
 
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:
<syntaxhighlight lang="raku" perl6line>constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *;
say @x[1000]; # prints 1.64393456668156</langsyntaxhighlight>
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:
 
<syntaxhighlight lang="raku" perl6line>constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*;
say ζish[1000];</langsyntaxhighlight>
 
Perhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization:
<syntaxhighlight lang="raku" perl6line>use experimental :cached;
sub ζ($s) is cached { [\+] 1..* X** -$s }
say ζ(2)[1000];</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight Ravenlang="raven">0 1 1000 1 range each 1.0 swap dup * / +
"%g\n" print</langsyntaxhighlight>
{{out}}
<pre>1.64393</pre>
Line 2,439 ⟶ 2,744:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
s: 0
repeat n 1000 [ s: 1.0 / n ** 2 + s ]
print s
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
===sums specific terms===
<langsyntaxhighlight 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*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
Line 2,457 ⟶ 2,762:
end /*k*/
 
say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,465 ⟶ 2,770:
===sums with running total===
This REXX version shows the &nbsp; ''running total'' &nbsp; for every 10<sup>th</sup> term.
<langsyntaxhighlight 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*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
Line 2,483 ⟶ 2,788:
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. */</langsyntaxhighlight>
'''output''' &nbsp; when using the input of: &nbsp; <tt> 1000000000 </tt>
<pre>
Line 2,506 ⟶ 2,811:
 
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''.
<langsyntaxhighlight 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*/
if N=='' | N=="," then N=1000 /*Not specified? Then use the default.*/
Line 2,526 ⟶ 2,831:
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. */</langsyntaxhighlight>
'''output''' &nbsp; when using the input of &nbsp; (one billion [limit], and one hundred decimal digits): &nbsp; <tt> &nbsp; 1000000000 &nbsp; 100 </tt>
<pre>
Line 2,554 ⟶ 2,859:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
<lang Ring>
sum = 0
for i =1 to 1000
Line 2,561 ⟶ 2,866:
decimals(8)
see sum
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
<syntaxhighlight lang="rlab">
<lang RLaB>
>> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6
-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}}==
<langsyntaxhighlight lang="ruby">puts (1..1000).injectsum{ |sum, x| sum + 1.01r / x ** 2 }.to_f</langsyntaxhighlight>
{{out}}
<pre>
Line 2,577 ⟶ 2,895:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">
for i =1 to 1000
sum = sum + 1 /( i^2)
next i
print sum</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const LOWER: i32 = 1;
const UPPER: i32 = 1000;
 
Line 2,596 ⟶ 2,914:
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}
</syntaxhighlight>
</lang>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data _null_;
s=0;
do n=1 to 1000;
Line 2,606 ⟶ 2,924:
e=s-constant('pi')**2/6;
put s e;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">scala> 1 to 1000 map (x => 1.0 / (x * x)) sum
res30: Double = 1.6439345666815615</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (sum a b fn)
(do ((i a (+ i 1))
(result 0 (+ result (fn i))))
Line 2,619 ⟶ 2,937:
 
(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction
(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal</langsyntaxhighlight>
 
More idiomatic way (or so they say) by tail recursion:
<langsyntaxhighlight lang="scheme">(define (invsq f to)
(let loop ((f f) (s 0))
(if (> f to)
Line 2,630 ⟶ 2,948:
;; 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</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,648 ⟶ 2,966:
end for;
writeln(sum digits 6 lpad 8);
end func;</langsyntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">print( +/[1/k**2 : k in [1..1000]] );</syntaxhighlight>
{{out}}
<pre>1.64393456668156</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">say sum(1..1000, {|n| 1 / n**2 })</langsyntaxhighlight>
 
Alternatively, using the ''reduce{}'' method:
<langsyntaxhighlight lang="ruby">say (1..1000 -> reduce { |a,b| a + (1 / b**2) })</langsyntaxhighlight>
 
{{out}}
Line 2,665 ⟶ 2,988:
Manually coerce it to a float, otherwise you will get an exact (and slow) answer:
 
<langsyntaxhighlight lang="slate">((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">( (1 to: 1000) fold: [:sum :aNumber |
sum + (aNumber squared reciprocal) ] ) asFloat displayNl.</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight SQLlang="sql">create table t1 (n real);
-- this is postgresql specific, fill the table
insert into t1 (select generate_series(1,1000)::real);
Line 2,678 ⟶ 3,037:
select 1/(n*n) as recip from t1
) select sum(recip) from tt;
</syntaxhighlight>
</lang>
Result of select (with locale DE):
<pre>
Line 2,688 ⟶ 3,047:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">function series(n) {
return(sum((n..1):^-2))
}
 
series(1000)-pi()^2/6
-.0009995002</langsyntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
func sumSeries(var n: Int) -> Double {
var ret: Double = 0
Line 2,708 ⟶ 3,067:
 
output: 1.64393456668156
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="text">
Swift also allows extension to datatypes. Here's similar code using an extension to Int.
 
Line 2,733 ⟶ 3,092:
 
y = 1000.sumSeries()
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Line 2,739 ⟶ 3,098:
=== Using Expansion Operator and mathop ===
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">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</langsyntaxhighlight>
 
=== Using Loop ===
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc partial_sum {func - start - stop} {
Line 2,759 ⟶ 3,118:
set S {x {expr {1.0 / $x**2}}}
 
partial_sum $S from 1 to 1000 ;# => 1.6439345666815615</langsyntaxhighlight>
 
=== Using tcllib ===
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 2,772 ⟶ 3,131:
set S {x {expr {1.0 / $x**2}}}
 
sum_of $S [range 1 1001] ;# ==> 1.6439345666815615</langsyntaxhighlight>
 
The helper <code>range</code> procedure is:
<langsyntaxhighlight lang="tcl"># a range command akin to Python's
proc range args {
foreach {start stop step} [switch -exact -- [llength $args] {
Line 2,790 ⟶ 3,149:
}
return $range
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 2,796 ⟶ 3,155:
{{trans|TI-89 BASIC}}
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
<langsyntaxhighlight lang="ti83b">
∑(1/X²,X,1,1000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,807 ⟶ 3,166:
 
The TI-83 does not have the new summation notation, and caps lists at 999 entries.
<langsyntaxhighlight lang="ti83b">sum(seq(1/X²,X,1,999))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,815 ⟶ 3,174:
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang="ti89b">∑(1/x^2,x,1,1000)</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 2,823 ⟶ 3,182:
Variant A1: limit the list generation inside the <code>gen</code> operator.
 
<langsyntaxhighlight lang="txr">txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]'
1.64393456668156</langsyntaxhighlight>
 
Variant A2: generate infinite list, but take only the first 1000 items using <code>[list-expr 0..999]</code>.
 
<langsyntaxhighlight lang="txr">txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]'
1.64393456668156</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="txr">txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]'
1.64393456668156</langsyntaxhighlight>
 
Variant C: unravel the chain in Variant B using straightforward nesting.
 
<langsyntaxhighlight lang="txr">txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]'
1.64393456668156</langsyntaxhighlight>
 
Variant D: bring Variant B's inverse square calculation into the fold, eliminating mapcar. Final answer.
 
<langsyntaxhighlight lang="txr">txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]'
1.64393456668156</langsyntaxhighlight>
 
=={{header|Unicon}}==
Line 2,850 ⟶ 3,209:
 
=={{header|UnixPipes}}==
<langsyntaxhighlight lang="bash">term() {
b=$1;res=$2
echo "scale=5;1/($res*$res)+$b" | bc
Line 2,867 ⟶ 3,226:
}
 
(echo 3; echo 1; echo 4) | fold sum</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 2,875 ⟶ 3,234:
function, plus. The rest the expression constructs the series
by inverting the square of each number in the list from 1 to 1000.
<langsyntaxhighlight Ursalalang="ursala">#import flo
#import nat
 
#cast %e
 
total = plus:-0 div/*1. sqr* float*t iota 1001</langsyntaxhighlight>
output:
<pre>1.643935e+00</pre>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">
public static void main(){
int i, start = 1, end = 1000;
Line 2,895 ⟶ 3,254:
stdout.printf("%s\n", sum.to_string());
}
</syntaxhighlight>
</lang>
 
Output:
Line 2,903 ⟶ 3,262:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function sumto(n As Integer) As Double
Dim res As Double
For i = 1 To n
Line 2,912 ⟶ 3,271:
Public Sub main()
Debug.Print sumto(1000)
End Sub</langsyntaxhighlight>{{out}}
<pre> 1,64393456668156 </pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Sum of a series
for i=1 to 1000
s=s+1/i^2
next
wscript.echo s </langsyntaxhighlight>
{{out}}
<pre>
Line 2,929 ⟶ 3,288:
{{trans|VBScript}}
{{works with|Visual Basic .NET|2013}}
<langsyntaxhighlight lang="vbnet">' Sum of a series
Sub SumOfaSeries()
Dim s As Double
Line 2,937 ⟶ 3,296:
Next 'i
Console.WriteLine(s)
End Sub </langsyntaxhighlight>
{{out}}
<pre>
1.64393456668156
</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}}==
<langsyntaxhighlight WDTElang="wdte">let s => import 'stream';
 
s.range 1 1001
Line 2,950 ⟶ 3,338:
-> s.reduce 0 +
-- io.writeln io.stdout
;</langsyntaxhighlight>
 
{{out}}
Line 2,956 ⟶ 3,344:
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@sum !*#~V1Sn @to 1000 ; returns 1.6439345666815615</langsyntaxhighlight>
<langsyntaxhighlight lang="wortel">@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</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="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)")</langsyntaxhighlight>
 
{{out}}
Line 2,975 ⟶ 3,363:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="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);
]</langsyntaxhighlight>
 
Output:
Line 2,988 ⟶ 3,376:
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">(1./indgen(1:1000)^2)(sum)</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="zkl">[1.0..1000].reduce(fcn(p,n){ p + 1.0/(n*n) },0.0) //-->1.64394</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">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</langsyntaxhighlight>
{{out}}
<pre>
885

edits