Fixed-point arithmetic: Difference between revisions

Content deleted Content added
No edit summary
Tags: Mobile edit Mobile web edit Advanced mobile edit
Tags: Mobile edit Mobile web edit Advanced mobile edit
Line 108:
{{Unreferenced section|date=May 2023}}
===Addition and subtraction===
To add or subtract two values with the same implicit scaling factor, it is sufficient to add or subtract the underlying integers; the result will have their common implicit scaling factor and can thus be stored in the same program variables as the operands. These operations yield the exact mathematical result, as long as no [[arithmetic overflow|overflow]] occurs—that is, as long as the resulting integer can be stored in the receiving program [[variable (computing)|variable]]. If overflow happens, it occurs like with ordinary integers of the same signedness. In the unsigned case, the overflow behaviour is well-known as a [[finite ring]].

If the operands have different scaling factors, then they must be converted to a common scaling factor before the operation.
 
===Multiplication===
To multiply two fixed-point numbers, it suffices to multiply the two underlying integers, and assume that the scaling factor of the result is the product of their scaling factors. The result will be exact, with no rounding, provided that it does not overflow the receiving variable. (Specifically, with integer multiplication, the product is up to twice the width of the two factors.)
 
For example, multiplying the numbers 123 scaled by 1/1000 (0.123) and 25 scaled by 1/10 (2.5) yields the integer 123×25 = 3075 scaled by (1/1000)×(1/10) = 1/10000, that is 3075/10000 = 0.3075. As another example, multiplying the first number by 155 implicitly scaled by 1/32 (155/32 = 4.84375) yields the integer 123×155 = 19065 with implicit scaling factor (1/1000)×(1/32) = 1/32000, that is 19065/32000 = 0.59578125.