[Tutor] problems with numbers in my python code

Hugo González Monteverde hugonz-lists at h-lab.net
Fri Mar 10 15:43:09 CET 2006


Hi,


> However, I can't seem to get the program to treat the numbers as numbers. If
> I put them in the dictionary as 'THE' = int(0.965) the program returns 1.0
> and if I put 'THE' = float(0.965) it returns 0.96555555549 or something
> similar. Neither of these are right! I basically need to access each item in
> the string as a number, because for my last function I want to multiply them
> all together by each other. 

The latter is right. Floating point numbers have limited precision 
(limited by the number of bits used in the representation) The exact 
number .965  does not exist in the representation for your computer, but 
  smart displaying can be done:

 >>> .965
0.96499999999999997
 >>> print .965
0.965
 >>> var = .965
 >>> var
0.96499999999999997
 >>> print var
0.965
 >>> str(var)
'0.965'
 >>> repr(var)
'0.96499999999999997'
 >>>

Take a look at apprendix B in the tutorial: Floating Point Arithmetic: 
Issues and Limitations

http://docs.python.org/tut/node16.html

Also the decimal module may be the solution to your problem:
http://docs.python.org/tut/node13.html#SECTION0013800000000000000000

Hope this clarifies things a bit.

Hugo


> 
> I have tried two bits of code for this last bit, but neither are working
> (I'm not sure about the first one but the second one should work I think if
> I could figure out how to return the values as numbers):
> 
> 1st code 
> value = codons[x] * codons[x+1]
> x = (int)
> x = 0
> 
> print value
> 
> x +=2
> 
> if (x<r):
>     new_value = value * codons[x]
>     value = new_value
>     x +=1
> else:
>     print new_value
> 
> This gives the error message 
> Traceback (most recent call last):
>   File "C:\Python24\code2", line 88, in -toplevel-
>     value = codons[x] * codons[x+1]
> NameError: name 'x' is not defined
>  
> Code 2 - the most likely code
> prod = 1
> for item in (codons): prod *= item
> prod
> print prod
> 
> Gives this error message:
> Traceback (most recent call last):
>   File "C:\Python24\code2", line 90, in -toplevel-
>     for item in (codons): prod *= item
> TypeError: can't multiply sequence by non-int
> 
> 
> Can anyone help me solve this problem?
> Thanks.
> 
> --
> View this message in context: http://www.nabble.com/problems-with-numbers-in-my-python-code-t1259271.html#a3339964
> Sent from the Python - tutor forum at Nabble.com.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list