Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: run time of math problem



> On Mar 19, 2021, at 7:18 PM, Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
> 
> ... I'd expect the thing to run a teeny bit faster but in fact it
> runs about 15% slower.  Is that explicable?  Does zsh prefer
> calculations done in steps with variables for each step?  Or is this
> just some little anomaly?  Things might not optimize every time.

Think about how your change affects your algorithm.

>   for ((level=1; level<100; level++)); do
>        sum=
>        remainder=$(( (level - 1.0) / level ))
>        for ((terms=level; terms; terms--)); do
>            sum+=$(( remainder**(terms - 1) ))
>        done
>        divided=$(( sum * (1.0 / level) ))
>        echo for level: $level, survival: $divided
>   done

Here, you evaluate "(level - 1.0) / level" 99 times.

> Now if I avoid the 'remainder' variable:
> 
>     for ((level=1; level<100; level++)); do
>         sum=
>         for ((terms=level; terms; terms--)); do
> 
>            # 'remainder' calculation done directly here:
>            sum+=$(( ( (level - 1.0) / level )**(terms - 1) ))
>        done
>        divided=$(( sum * (1.0 / level) ))
>        echo for level: $level, survival: $divided
>   done

Here, you evaluate it 4950 times.

vq




Messages sorted by: Reverse Date, Date, Thread, Author