Fixed-point arithmetic: Difference between revisions

Content deleted Content added
Tags: Mobile edit Mobile web edit Advanced mobile edit
Tags: Mobile edit Mobile web edit Advanced mobile edit
Line 128:
 
===Division===
ToThe dividedivision twoof fixed- point numbers, oneis takesbest theunderstood integeras quotientthe division of theirtwo underlyingfractions integersof andpotentially assumesdifferent that thedenominators (scaling factorfactors). isWith the{{frac|p|q}} quotientand of{{frac|r|s}} their(where scalingp factors.q r Ins generalare all integers), the firstnaive divisionapproach requiresis roundingto and thereforerearrange the resultfraction isto notform exact.a new scaling factor:
 
: (p/q) / (r/s) = (p/r) / (s/q)
 
As always, integer divisions involve rounding, so this is not necessarily the most accurate — large losses of precision happens when p/r is calculated.
 
For example, division of 3456 scaled by 1/100 (34.56) and 1234 scaled by 1/1000 (1.234) yields the integer 3456÷1234 = 3 (rounded) with scale factor (1/100)/(1/1000) = 10, that is, 30. As another example, the division of the first number by 155 implicitly scaled by 1/32 (155/32 = 4.84375) yields the integer 3456÷155 = 22 (rounded) with implicit scaling factor (1/100)/(1/32) = 32/100 = 8/25, that is 22×32/100 = 7.04.
 
IfOne thetrick resultto isreduce notor exact,even eliminate the rounding error introducedis byto convert the roundingdividend canto bea reducedsmaller orscaling evenfactor eliminated(with bycorrespondingly convertingmore digits or bits preserved for the dividendcalculation). toIf awe smallerreduce the scaling factor. by ''n'' times, we effectively have:

: (p/q) / (r/s) = (np/nq) / (r/s) = (np/r) / (s/nq)

For example, if ''ra'' = 1.23 is represented as 123 with scaling 1/100, and ''sb'' = 6.25 is represented as 6250 with scaling 1/1000, then simple division of the integers yields 123÷6250 = 0 (rounded) with scaling factor (1/100)/(1/1000) = 10. If ''ra'' is first converted to 1,230,000 with scaling factor 1/1000000, the result will be 1,230,000÷6250 = 197 (rounded) with scale factor 1/1000 (0.197). The exact value 1.23/6.25 is 0.1968.
 
===Scaling conversion===