Math problem

Kay C Lan lan.kc.macmail at gmail.com
Fri Feb 17 05:27:43 EST 2012


On Tue, Feb 14, 2012 at 6:09 AM, Bob Sneidar <bobs at twft.com> wrote:

> Hey there it is! I was looking for a strictly mathematical method but that
> will do nicely.
>
> Not sure how Paul's response could be the answer as it seems to miss an
important step.

"--take the difference in pIncrement units, rounded up…"

There is no LC function that rounds up, certainly round() doesn't do it.
When I test Paul's function against 09:00 AM and 10:00:01 AM I get 1, not
1.25 as you required. The trick is to force LC to round up.

Here is my offering. Note, I've created it as something to go in a button
to test first, so it uses mouseUp, and includes a bunch of lines that would
need to be removed when used as a function. As a function pIncrement must
come in as a whole number of seconds.

I included the ability to test increments other than 15 min.

I preset it to 20min increments, not 15 as per your OP, to demonstrate the
use of round() to round up OR DOWN to a specific number of places. In the
case of 09:00 AM and 10:20:01 AM I get the answers below.

1.333333 - Paul's solution
1.666667 - one line full precision
1.67 - one line 2 decimal place

Be careful of line breaks, there should be 28 lines:


on mouseUp
    --below not required if used as a function
    ask question "What Increment? In minutes." with "20" titled "Increment
To Use"
    if (60 mod it = 0) then
        put it*60 into pIncrement --converted to sec
    else
        --number not divisible into 60 so not usable
        exit to top
    end if

    put "09:00 AM" into pStartTime
    put "10:20:01 AM" into pEndTime
    --above not required if used as a function
    ------
    --FUNCTION BELOW -- pIncrement must be in sec
    ------

    convert pStartTime to seconds
    convert pEndTime to seconds

    --Pauls solution
    put (round(((pEndTime - pStartTime)/pIncrement),0)/(3600/pIncrement)) &
" - Paul's solution" into msg
    -- one line with full precision
    put cr & round(((pEndTime + (pIncrement/2) - 1 -
pStartTime)/pIncrement),0)/(3600/pIncrement) & " - one line full precision"
after msg
    -- one line 2 decimal place, using another round()
    put cr & round(round(((pEndTime + (pIncrement/2) - 1 -
pStartTime)/pIncrement),0)/(3600/pIncrement),2) & " - one line 2 decimal
place" after msg

end mouseUp

Basically I'm adding half the increment to force LC to round up. The
problem is, if you have 10.0 and add 0.5 to it, 10.5 rounds to 11, which is
not what you want. To prevent that I've subtracted your level of precision.
So 10 + 0.49 rounds down to 10; whilst 10.01, 10.2, and 10.99 + 0.49 will
round up to 11.0

HTH



More information about the use-livecode mailing list