Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: run time of math problem
- X-seq: zsh-users 26585
- From: Oliver Kiddle <opk@xxxxxxx>
- To: Ray Andrews <rayandrews@xxxxxxxxxxx>
- Cc: Zsh Users <zsh-users@xxxxxxx>
- Subject: Re: run time of math problem
- Date: Sat, 20 Mar 2021 00:52:39 +0100
- Archived-at: <https://zsh.org/users/26585>
- Archived-at: <http://www.zsh.org/sympa/arcsearch_id/zsh-users/2021-03/41359-1616197959.973399%400dqq.OWmi.jXTb>
- In-reply-to: <a1c6d13a-7a04-fba4-4419-7eccbf013824@eastlink.ca>
- List-id: <zsh-users.zsh.org>
- References: <a1c6d13a-7a04-fba4-4419-7eccbf013824@eastlink.ca>
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