Routine for DoubleWord/ ByteC

Jeremy Leach

Senior Member
This is another maths routine for calculating an exact result without overflow. It's approximately 98 bytes long.

You pass the routine the DoubleWord and ByteC values and it calculates the result, leaving the result in ResultWhole and ResultRemainder, where the remainder is a decimal remainder (ie 6 for .6).

The DoubleWord value is made up of a least and most-significant Word, LSW and MSW.

It assumes the result of the calculation is going to fit into a Word.

The explanation for how it works is with the code.

The routine could be useful for averaging, where you accumulate a running sum in a DoubleWord then want to work out the running average over C samples.

It can also be used for calculating WordA * WordB / ByteC (MSW = WordA ** WordB, LSW = WordA * WordB)
 

Attachments

Last edited:

fernando_g

Senior Member
Thanks Jeremy; someday in the future, when I require double word calculations, I'll definitively use your code.

One thing that I noticed is that it is only suitable for the larger members of the PICAXE family, as the word variable W7 will preclude running this code in say, a 14M.
 

westaust55

Moderator
Concur and thanks Jeremy.

Had started on such a routine but was side tracked for now with 1-Wire experiemnts and had left of with still some coarse error in my routine.
Admittedly I was dealing with division of 6 byte values by bytes/words but I am sure your code will help when I get back into it.
 

hippy

Technical Support
Staff member
It should be possible to fold some of the calculations which would make them longer but use less variables, eg

A = B / C
D = A + E
F = A + G

can become

D = B/C + E
F = B/C + G

@ Jeremy : Not sure the remainder is right ( physical and simulating 20X2 ) ...

MSW = $0001
LSW = $2345
ByteC = 16

gave correct result $1234 but remainder $3.
 

westaust55

Moderator
@ Jeremy : Not sure the remainder is right ( physical and simulating 20X2 ) ...

MSW = $0001
LSW = $2345
ByteC = 16

gave correct result $1234 but remainder $3.
I believe the remainder of "3" is correct in the context/accuracy of the maths.

That is remainder = 0.3 * 16 = 4.8 sort of right accuracy

if the remainder were to 2 places ==> 31
0.31 * 16 = 0.496 = ~5 which is correct
 
Top