Difference between revisions of "CSC231 Homework 8 2014"
(Created page with "--~~~~ ---- <onlydft> =Problem #1= <br /> Python seems to be more "clever" about dealing with variables of different types than other languages. For example, if you write a...") |
|||
Line 10: | Line 10: | ||
Sometimes, however, Python seems to behave in unexpected ways. To see an example of this, get the following Python program: [[CSC231 sum_of_floats.py | sum_of_floats.py]], and study it. It creates a list of 10 random floating-point numbers, each one the result of picking a random real number between 0 and 1.0, which is then multiplied by 10 raised to some other random integer in the range -40 to +40. | Sometimes, however, Python seems to behave in unexpected ways. To see an example of this, get the following Python program: [[CSC231 sum_of_floats.py | sum_of_floats.py]], and study it. It creates a list of 10 random floating-point numbers, each one the result of picking a random real number between 0 and 1.0, which is then multiplied by 10 raised to some other random integer in the range -40 to +40. | ||
− | The program then computes the sum of the ten numbers as stored in the list. That's sum1. Next it sorts the list in increasing order and computes the sum again, this time saving it into sum2. Finally, it reverses the list so that it is sorted in decreasing order, and computes the sum of the numbers which it stores in sum3. It then | + | The program then computes the sum of the ten numbers as stored in the list. That's sum1. Next it sorts the list in increasing order and computes the sum again, this time saving it into sum2. Finally, it reverses the list so that it is sorted in decreasing order, and computes the sum of the numbers which it stores in sum3. It then and displays the list, and the three sums. Observe the least significant digits of the 3 sums for differences. |
'''Question 1''': Explain why the 3 sums are usually the same, but ''sometimes'' not equal. Hints: the 32-bit IEEE Floating-Point format which we saw in class has a lot to do with it. | '''Question 1''': Explain why the 3 sums are usually the same, but ''sometimes'' not equal. Hints: the 32-bit IEEE Floating-Point format which we saw in class has a lot to do with it. |