Saturday, May 7, 2011

Basic Math : Basic Summation

Given the basic expression for summation:
\[ \begin{align}
\sum_{i=1}^n i
\end{align}
\]
Calculating the scalar sum:

1 + 2 + 3 + 4 ...

public class ScalarSum {
public int sum(final f f, int j, int n) {
int sum = 0;
for (int index = j; index <= n; index++) {
sum = sum + f.$(index);
}
return sum;
}
public interface f {
public int $(final int x);
}
public static class Fx implements f {
public int $(int x) {
return x;
}
}
public static class Fx2 implements f {
public int $(int x) {
return x*x;
}
}
public static class Fx3 implements f {
public int $(int x) {
return x*x*x;
}
}
}
System.out.println("Sum: " + new ScalarSum().sum(new ScalarSum.Fx(), 1, 100));

With haskell:

summation1 :: Integer -> Integer -> Integer
summation1 x y = summation' x y 0
summation' :: Integer -> Integer -> Integer -> Integer
summation' x y sum = if (y<x) then sum else summation' x (y-1) (sum+y)

sum2 :: [Integer] -> Integer -> Integer
sum2 xs y = foldl (+) 0 xs

main :: IO ()
main = print("Output : " ++ show(summation1 0 100) ++ " sum2= " ++ show(sum2 [0..100] 0))


sum(n=1 to 100) = 5050

No comments:

Post a Comment