help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Can Bash do simple math?


From: alex xmb sw ratchev
Subject: Re: Can Bash do simple math?
Date: Tue, 6 Aug 2024 18:24:13 +0200

On Tue, Aug 6, 2024, 17:53 Greg Wooledge <greg@wooledge.org> wrote:

> On Tue, Aug 06, 2024 at 17:08:23 +0200, alex xmb sw ratchev wrote:
> > i really dont see why 60
>
> Because there are 60 seconds in each minute, and 60 minutes in each hour.
>
> Let's say you measure how long a program takes to run, and it ends up
> being 179 seconds.  You'd like to convert this number (179) to an
> interval expressed as "x minutes and y seconds".
>
> There are a few ways you can do this.  They all give you the same answer.
>
> The way that I find simplest to understand is always to divide by the
> next conversion factor.  So:
>
>  1) We divide 179 by 60, to get the number of minutes.
>

u misread big
the users original code
makes , seconds minus math
the currency of it is still 1second

now look what u write
' to get minutes '

i say users code has
seconds = diffinseconds % 60
not
minutes = diffinseconds % 60

i use / 60 anyway
i must benchmark somewhen

    We're using integer division, so any fractions are discarded.
>     179 / 60 = 2
>     So the final answer includes "2 minutes" as the first component.
>
>  2) Now that we know how many whole minutes there are, we remove those
>     from the original number.
>     2 * 60 = 120
>     We decrease the original number by 120.
>     179 - 120 = 59
>
>  3) The amount that's left over (59) is the number of seconds.
>     So our final answer is "2 minutes and 59 seconds".
>
> The conversion that the OP used is very similar to this, except they
> went for hours, minutes and seconds.
>
> Let's say you run a different program and it takes 7701 seconds, and
> you'd like to convert this to "x hours, y minutes and z seconds".  We
> can apply a similar recipe:
>
>  1) Divide 7701 by 3600 to get the number of whole hours.
>     7701 / 3600 = 2
>     "2 hours"
>
>  2) Subtract the whole hours from the original number.
>     7701 - (2 * 3600) = 501
>
>  3) Divide by 60 to get the number of minutes.
>     501 / 60 = 8
>     "8 minutes"
>
>  4) Subtract the whole minutes from the original number
>     501 - (8 * 60) = 21
>
>  5) The remaining number is the number of seconds.
>     "21 seconds"
>
> So in this case, our final answer is "2 hours, 8 minutes and 21 seconds".
>
> The OP chose to use slightly different recipes, which involve modulus
> and which don't decrease the total as we go.  That's fine.  As I said,
> there are different ways to do it, which all give the same answer.
>
>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]