Need help using Modulus to figure average
Don M
Posts: 1,652
I know I read earlier that Modulus was used to get the remainder of a division equation. So I wanted to use it to figure an average of x events but I don't get the right answer.
I was expecting my answer to be 39.4 (39.3571.... rounded up?) but it displays 39.5
What am I doing wrong?
Thanks.
Don
secs := 551 ' Total events time term.dec(secs / 14) ' Get average of 14 events term.tx(".") term.dec(secs // 14)
I was expecting my answer to be 39.4 (39.3571.... rounded up?) but it displays 39.5
What am I doing wrong?
Thanks.
Don
Comments
So what you ordered is what you got.
If you do it as
You should get two decimal places.
More logical order would be:
You can then farm the printing to a separate routine as the divide by 14 isn't tangled up with the printing
of the value. Note that each decimal digit is printed separately so that x.01 doesn't print as x.1
I'll add a link in a minute or too to the method.
I usually have a constant I call "PSEUDO_MULTIPLIER" so I can easily change the amount the integer is scaled.
In this case, I'll just use the magic number "100". You could use any other power of ten number (within reason) to scale the number. You do need to make sure your scaling number doesn't cause a 32-bit overflow.
The above should display the seconds with two digits after the decimal point.
The last significant digit is not rounded. A quick and dirty way to make sure the last digit is rounded is to add half of the dividing number to the original value. In this case you'd use:
The above should result in the number being correctly rounded. I haven't tested the code myself but I'm pretty sure it should work.
In the real world "pseudo real numbers" are known as "fixed point".
Whilst a scale factor that is a power of ten is nice for what's gong on here remember other scale factors can be used. Powers of two are convenient because the scaling can be done with a fast shift operation instead of a slow multiply.
Floating divide of 551/14 = 39.3571428571429.
So ite answer should be "39.36" not "39.35".
Try this: This gives "39.36"
These integer functions do "Truncations"
By simply adding 0.5 to the value before thew truncation the answer is correct.
In this case I essentially doubled the value and added 1 then divide by 2.
Duane J