How do I convert a simple algorithm to a mathematical notation?

2.1k Views Asked by At

I am trying to write a simple algorithm given below in mathematical notation. I wrote the formula up to a certain point, but I have no idea of restrictions. For example, I used the NULL statement even though it was not "else". It also needs a "break" statement or equivalent.

    var thr = 0.5;
    var M = 100;
    var sum = 0;
    var T = 0;

    for i 0 to G
    {
      sum = sum + i;
      if sum/M >= thr then
      {
        T = i;
        break;
      }
    }

  return T;

My math notations; I defined "sum" in equation as follows. $$sum = \sum_{j=0}^{i}j$$

(Eq.1)$$T = \sum_{i=0}^{G}f={ \begin{cases} i & \frac{\sum_{j=0}^{i}j}{M}\geq thr\\ \mathrm{NULL} & \text{otherwise} \end{cases}}$$ (Eq.2)$$T = \sum_{i=0,f\neq \mathrm{NULL}}^{G}f={ \begin{cases} i & \frac{\sum_{j=0}^{i}j}{M}\geq thr\\ \mathrm{NULL} & \text{otherwise} \end{cases}}$$

Thank you very much for your help already.

3

There are 3 best solutions below

4
On BEST ANSWER

The idea here is that $T$ is equal to $i$, where $i$ is the first index in the loop for which $\verb|sum|\,/M \ge \verb|thr|$. This can be written in a formula as follows: $$ T = \begin{cases}0 &\tfrac1M\textstyle\sum_{j=0}^Gj<\verb|thr|\\\min\{i\mid i\in \{0,1,\dots,G\},\tfrac1M\textstyle\sum_{j=0}^ij\ge \verb|thr|\} & \text{Otherwise} \end{cases} $$ So you take the set of $i$ for which the loop would have stopped by the $i^\text{th}$ iteration, and declare $T$ to be the smallest (minimum) of this set.

6
On

You need to think about what the code is doing, not just translate the code. Wehn you write $$sum = \sum_{j=0}^{i}i$$ there is a small error that the iteration variable is $j$ so you should write $$sum = \sum_{j=0}^{i}j$$ More importantly, $sum$ is changing through the computation, so it would be better to write $$sum(i) = \sum_{j=0}^{i}j$$ then you should perform the sum and write $$sum(i)=\frac 12i(i+1)$$ Then $T$ is the $i$ for which $sum$ exceeds $M\cdot thr$. Some analysis will show that $$T=\left\lceil\frac 12(-1+\sqrt{1+8\cdot M\cdot thr}) \right \rceil$$ which is much more useful for someone trying to understand your code. This last shows a way to get the result without iteration as well.

0
On

Your code is iterating $i$ from $0$ to $G$ and cumulatively incrementing the $\text{sum}$ by that iterator, breaking when $\text{sum}/M\geq \text{thr}$ (or $\text{sum}\geq M\times\text{thr}$ when rounding is not an issue ). Only when breaking is $T$ set to the iterator, otherwise it is left at zero.

Since $\sum_{i=0}^n i =\tfrac{n\,(n+1)}2$ , and the values of $M$ and $\text{thr}$ are hard coded constants: $100$ and $0.5$, that code should result in

$$\begin{align}T & =\begin{cases} 0 &:& {G\,(G+1)}< 100\\ \min\{t\in\{0..G\}: t(t+1)\geqslant 100\} &:&\text{otherwise} \end{cases} \\ &= \begin{cases} 0 &:& G<10\\ 10 &:& G\geq 10\end{cases}\end{align}$$