Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: run time of math problem
- X-seq: zsh-users 26583
- From: Lawrence Velázquez <vq@xxxxxxxxx>
- To: Ray Andrews <rayandrews@xxxxxxxxxxx>
- Cc: zsh-users@xxxxxxx
- Subject: Re: run time of math problem
- Date: Fri, 19 Mar 2021 19:46:16 -0400
- Archived-at: <https://zsh.org/users/26583>
- Archived-at: <http://www.zsh.org/sympa/arcsearch_id/zsh-users/2021-03/A78ABFDE-07C4-40E5-A9CD-6DC3B2C45867%40larryv.me>
- In-reply-to: <a1c6d13a-7a04-fba4-4419-7eccbf013824@eastlink.ca>
- List-id: <zsh-users.zsh.org>
- References: <a1c6d13a-7a04-fba4-4419-7eccbf013824@eastlink.ca>
> 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