Sum of a series: Difference between revisions
Content added Content deleted
(Sum a finite series. Started with C++ example) |
(Added Java example) |
||
Line 31: | Line 31: | ||
} |
} |
||
</pre> |
</pre> |
||
=={{header|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); |
|||
} |
|||
} |
Revision as of 04:49, 22 February 2008
Sum of a series
You are encouraged to solve this task according to the task description, using any language you may know.
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.
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 ) ); }
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); } }