Sum of a series: Difference between revisions
Content added Content deleted
No edit summary |
(Added J solution.) |
||
Line 59: | Line 59: | ||
pi pi f* 6e f/ f. \ 1.64493406684823 |
pi pi f* 6e f/ f. \ 1.64493406684823 |
||
=={{header|J}}== |
|||
S=: % @ *: NB. inverse of square of input |
|||
+/ S >: i. 1000 |
|||
1.64393 |
|||
(*:o.1)%6 NB. pi squared over six, for comparison |
|||
1.64493 |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
public class Sum{ |
public class Sum{ |
Revision as of 20:30, 22 February 2008
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Display the sum of a finite series for a given range.
For this task, use S(x) = 1/x^2, from 1 to 1000. (This approximates the Riemann zeta function. The Basel problem solved this: zeta(2) = π2/6.)
C++
#include <iostream> double f(double x); int main() { unsigned int start = 1; unsigned int end = 1000; double sum = 0; for( unsigned int x = start; x <= end; ++x ) { sum += f(x); } std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl; return 0; } double f(double x) { return ( 1 / ( x * x ) ); }
D
module series ; import std.stdio ; T series(T)(T function(int) t, int end, int start = 1 /* 0 if zero base*/ ) { T sum = 0 ; for(int i = start ; i <= end ; i++) sum += t(i) ; return sum ; } real term(int n){ return 1.0L/(n*n) ; } void main(){ writef("sum@[1..1000] = ", series(&term, 1000)) ; }
Forth
: sum ( fn start count -- fsum ) 0e bounds do i s>d d>f dup execute f+ loop drop ; :noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt ) 1 1000 sum f. \ 1.64393456668156 pi pi f* 6e f/ f. \ 1.64493406684823
J
S=: % @ *: NB. inverse of square of input +/ S >: i. 1000 1.64393 (*:o.1)%6 NB. pi squared over six, for comparison 1.64493
Java
public class Sum{ public static double f(double x){ return 1/(x*x); } public static void main(String[] args){ double start = 1; double end = 1000; double sum = 0; for(double x = start;x <= end;x++) sum += f(x); System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum); } }