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

MathJax Test - Looks like it is working


\[
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}
{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
\]
\[
\begin{align}
\sum_{k=0}^n a

\end{align}
\]
\[
\displaystyle \sum_{j=1}^n a_j = \left({a_1 + a_2 + \cdots + a_n}\right)
\]
\[
\displaystyle \sum_{k=m}^n f_k \left({g_{k+1} - g_k}\right) = \left({f_{n+1} g_{n+1} - f_m g_m}\right) - \sum_{k=m}^n \left({f_{k+1}- f_k}\right) g_{k+1}
\]