How to multiply by a fraction
John Abshier
Posts: 1,116
I remember (correctly or incorrectly) reading a method using the ** operator to multiply a value by a fraction. I cannot find the post with search. I thought it was
result := n ** (2^32 * f) where (2^32 * f) was calculated off line.
That appears to work for f < 0.5 but fails if f => 0.5 For n := 1000 and f := 0.5 I get -500. For f := 0.9 I get -101.
John Abshier
result := n ** (2^32 * f) where (2^32 * f) was calculated off line.
That appears to work for f < 0.5 but fails if f => 0.5 For n := 1000 and f := 0.5 I get -500. For f := 0.9 I get -101.
John Abshier
Comments
Then you would be mixing and matching floating point and integer math. That never works out.
I too remember this, but I think it was in the Basic STAMP book (way back when I was learning on that). I will see if I can look it up. But I think you create a 32-bit fraction, then ** it with the variable to get the upper 32-bits of the result.
Try something like 8 ** $80000000 .. does that equal 4? This would be the equivalent of 8 * 0.5 if I am thinking about this right.
f := .1 : 429496730
f := .2 : 858993459
f := .5 : 2147483648
f := .9 : 3865470566
John Abshier
I think you may need to fix the problem with a workaround. Shift the fraction value right one bit, and the integer left one bit.
Like:
Try,
result := (n * 2) ** (2^31 * f) * 2 where (2^31 * f) is calculated off line.
given n < 2^30
Oh, that's exactly what Bob is suggesting.
I'm always tripping over that sign trap when I use my habitual Stamp workarounds.
This worked for N < 2^30
John Abshier
John Abshier
signed/unsigned routines for fractions using signed integer math.
You need to convert it to Spin though.
Also explains the code.
regards peter
Take a look at my umath object in the OBEX. It includes an unsigned 32 * 32 (=64) / 32 mul/div method that lets you multiply an integer by any rational 32/32 fraction.
-Phil
Thanks. On the road and no internet once I get to my 87 year old Dad's house tomorrow afternoon. Thank you Road Runner for eliminating dial-up and not cutting my monthy bill.
John Absier