3.7: Division and Accuracy of an Equation
- Page ID
One thing to always keep in mind when using division with integers in any language (including Java, C/C++, etc) is that the results are truncated. This can lead to errors and different answers depending on the order of evaluation of the terms in the equation. For example, most 5th graders knows that "(10/3) *3 = 10", as the 3's should cancel. However in integer arithmetic the result of "10/3 = 3", and so "(10/3) *3 = 9" (not 10). However if you reverse the order of the operations you will find that "(10*3) / 3 = 10". This is shown in the following program.
Program 3-4: Program to show order of operations matters # File: Program3-4.asm # Author: Charles Kann # Purpose: To show the difference in result if ordering of multiplication and division are reversed. .text .globl main main: addi $sO, $zero, 10 # Store 10 and 3 in registers $sO and $s1 addi $s1, $zero, 3 div $s2, $sO, $s1 # Write out (10/3) * 3 mul $s2, $s2, $s1 addi $v0, $zero, 4 la $a0, result1 syscall addi $v0, $zero, 1 move $a0, $s2 syscall mul $s2, $s0, $s1 # Write out (10*3)/3 div $s2, $s2, $s1 addi $v0, $zero, 4 la $a0, result2 syscall addi $v0, $zero, 1 move $a0, $s2 syscall addi $v0, $zero, 10 #Exit program syscall .data result1: .asciiz "\n(10/3)*3 = " result2: .asciiz "\n(10*3)/3 = "
There are times (for example, when calculating a parent node in a Complete Binary Tree, which is covered in most textbooks on Data Structures) that division using truncation is desired. However, in general the simple rule to follow is when there is a mix of operations including division with integer numbers, code the expression to do the multiplication, addition, and subtraction before doing any division. This preserves the greatest accuracy of the result. This principal is true of integer arithmetic in any language, including any HLL.