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

Re: run time of math problem



Ray Andrews wrote:
>      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
>
> ... 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

Given that the latter approach has moved the remainder calculation
inside a loop and it needs to be repeated 50 times (on average), it
should be no surprise that it is slower.

If you want to optimise for speed, avoid string conversions and do, e.g.
  (( divided = sum * (1.0 / level) ))

You also may want to make sure to declare some of the variables as float
or integer or whatever. The sum+= line might end up being a string
concatenation if not.

Oliver




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