Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Floating point calculation problem

Thread Tools

Re: Floating point calculation problem

Steven D'Aprano
Posts: n/a
Schizoid Man wrote:

> I have a program that performs some calculations that runs perfectly on
> Python 2.7.3. However, when I try to execute it on Python 3.3.0 I get the
> following error:
> numer = math.log(s)
> TypeError: a float is required
> The quantity s is input with the following line: s = input("Enter s: ")
> To get rid of the compile error, I can cast this as a float:
> s = float(input("Enter s: "))
> However, then the result returned by the method is wrong. Why does this
> error occur in version 3.3.0 but not in 2.7.3? Why is the result incorrect
> when s is cast as a float (the casting is not required in 2.7.3)?

Others have already discussed the differences between input() in Python 2
and 3, but there's another difference that could be causing you to get the
wrong results: division in Python 2 defaults to *integer* division.

If you type a value like "3" (with no decimal point) into input, you will
get the int 3, not the float 3.0. Then if you divide by another integer, by
default you will get truncating integer division instead of what you
probably expect:

>>> num = input('Enter a value: ')

Enter a value: 3
>>> print num/2


Whereas if you type it with a decimal point, input() will turn it into a
float, and you will get float division:

>>> num = input('Enter a value: ')

Enter a value: 3.0
>>> print num/2


This does not happen in Python 3.x -- you always get floating point
division, even if both the numerator and denominator are ints.

You can fix this, and get the proper calculator-style floating point
division, in Python 2 by putting this line at the very top of your script:

from __future__ import division

This must appear before any other line of code; it can follow comments and
blank lines, but not code.


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Floating point calculation problem Chris Angelico Python 16 02-03-2013 04:22 AM
Re: Floating point calculation problem Chris Rebert Python 0 02-02-2013 10:47 AM
floating point calculation problem bei C++ 4 01-07-2010 09:01 PM
floating point calculation problem bei C++ 0 01-06-2010 02:43 AM
Floating point calculation problem Hyun chul Park Ruby 3 07-08-2008 09:15 AM