Difference between revisions of "CSC231 sum of floats.py"

From dftwiki3
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 
--[[User:Thiebaut|D. Thiebaut]] 20:45, 9 December 2008 (UTC)
 
--[[User:Thiebaut|D. Thiebaut]] 20:45, 9 December 2008 (UTC)
 
----
 
----
 
+
<br />
<code><pre>
+
<source lang="python">
 
# sum_of_floats.py
 
# sum_of_floats.py
 
# D. Thiebaut
 
# D. Thiebaut
Line 74: Line 74:
  
  
</pre></code>
+
</source>
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
[[Category:CSC231]][[Category:Python]]

Latest revision as of 10:38, 4 December 2014

--D. Thiebaut 20:45, 9 December 2008 (UTC)



# sum_of_floats.py
# D. Thiebaut
# Please use Python V 2.7 to run this program...
#
# generate a list of 10 random real numbers
# sum up the numbers 3 different ways:
#    a) without modifying the list
#    b) after sorting the list in increasing order
#    c) after sorting the list in decreasing order
#
# Typical output:
# List[0] = 7.735545e+036
# List[1] = 6.601143e+024
# List[2] = 5.969324e+024
# List[3] = 2.203093e+017
# List[4] = 7.594234e+009
# List[5] = 1.312106e+006
# List[6] = 3.241121e+004
# List[7] = 3.169280e-001
# List[8] = 3.387630e-019
# List[9] = 2.664266e-022
# sum1 = 7.73554468369732770000e+036
# sum2 = 7.73554468369732890000e+036
# sum3 = 7.73554468369732770000e+036
# 

import random
N = 10

def getSums():
    #--- create a list of 10 random numbers ---
    List = []
    for i in range( N ):
        List.append( random.random() * pow( 10, random.randint( -40, +40 ) ) )

    #--- sum up the list without preprocessing ---
    sum1 = 0
    for item in List:
        sum1 += item

    #--- sum up the list after first sorting it in increasing order ---
    sum2 = 0
    List.sort()
    for item in List:
        sum2 += item

    #--- sum up the list after first sorting it in DEcreasing order ---
    sum3 = 0
    List.reverse()
    for item in List:
        sum3 += item

    return (List, sum1, sum2, sum3)

def main():
    while True:
        #--- compute the sum of the same list 3 different ways ---
        (List, sum1, sum2, sum3) = getSums()

        #--- stop when the 3 sums are not equal ---        
        if ( sum1 != sum2 or sum1 != sum3 or sum2 != sum3 ):
            for i in range( len( List ) ):
                print "List[%d] = %e" % (i,List[i])
            print "sum1 = %1.20e" % sum1
            print "sum2 = %1.20e" % sum2
            print "sum3 = %1.20e" % sum3
            break
        
main()