473,396 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

float / rounding question

Hi I'm very much a beginner with Python.
I want to write a function to convert celcius to fahrenheit like this
one:

def celciusToFahrenheit(tc):
tf = (9/5)*tc+32
return tf

I want the answer correct to one decimal place, so
celciusToFahrenheit(12) would return 53.6.

Of course the function above returns 53.600000000000001.

How do I format it correctly?
Feb 25 '08 #1
13 2410
On Feb 25, 10:44 am, helen.m.fl...@gmail.com wrote:
Hi I'm very much a beginner with Python.
I want to write a function to convert celcius to fahrenheit like this
one:

def celciusToFahrenheit(tc):
tf = (9/5)*tc+32
return tf

I want the answer correct to one decimal place, so
celciusToFahrenheit(12) would return 53.6.

Of course the function above returns 53.600000000000001.

How do I format it correctly?
By the way, I tried this:

return '%2.1f' % tf but that returns a string instead of a number.

Any other suggestions?

Feb 25 '08 #2
sabatier wrote:
On Feb 25, 10:44 am, helen.m.fl...@gmail.com wrote:
>Hi I'm very much a beginner with Python.
I want to write a function to convert celcius to fahrenheit like this
one:

def celciusToFahrenheit(tc):
tf = (9/5)*tc+32
return tf

I want the answer correct to one decimal place, so
celciusToFahrenheit(12) would return 53.6.

Of course the function above returns 53.600000000000001.

How do I format it correctly?

By the way, I tried this:

return '%2.1f' % tf but that returns a string instead of a number.

Any other suggestions?
But you are asking for a string on your format string above.

And also formatting make no sense in other context since a number is a
number and 53.600000 and 53.6 are the same number (besides precision).

You are concerned with how numbers are represented in binary. When
displaying the value use the format string you shown above and all will
work.

Feb 25 '08 #3
25 February 2008 Monday 12:44:46 tarihinde he***********@gmail.com şunları yazmıştı:
Hi I'm very much a beginner with Python.
I want to write a function to convert celcius to fahrenheit like this
one:

def celciusToFahrenheit(tc):
tf = (9/5)*tc+32
return tf

I want the answer correct to one decimal place, so
celciusToFahrenheit(12) would return 53.6.

Of course the function above returns 53.600000000000001.

How do I format it correctly?
Use the round(number,digits) function:

tf = round((9/5)*tc+32,1)
Feb 25 '08 #4
Necmettin Begiter <ne***************@gmail.comwrote:
>25 February 2008 Monday 12:44:46 tarihinde he***********@gmail.com =C5=9Fun=
lar=C4=B1 yazm=C4=B1=C5=9Ft=C4=B1:
>Of course the function above returns 53.600000000000001.
=20
How do I format it correctly?

Use the round(number,digits) function:

tf =3D round((9/5)*tc+32,1)
>>53.6
53.600000000000001
>>round(53.6, 1)
53.600000000000001

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Feb 25 '08 #5
Mel
he***********@gmail.com wrote:
Hi I'm very much a beginner with Python.
I want to write a function to convert celcius to fahrenheit like this
one:

def celciusToFahrenheit(tc):
tf = (9/5)*tc+32
return tf

I want the answer correct to one decimal place, so
celciusToFahrenheit(12) would return 53.6.

Of course the function above returns 53.600000000000001.

How do I format it correctly?
print celcisuToFahrenheit (12)

will do fine.
Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>def celciusToFahrenheit(tc):
.... tf = (float(9)/5)*tc+32
.... return tf
....
>>celciusToFahrenheit (12)
53.600000000000001
>>print celciusToFahrenheit (12)
53.6
The straight value display from the interpreter pursues precision to
the bitter end, doing its formatting with the repr function. print
uses str formatting for a more expected result.

Mel.

Feb 25 '08 #6

<he***********@gmail.comwrote in message
news:d4**********************************@z17g2000 hsg.googlegroups.com...
| Hi I'm very much a beginner with Python.
| I want to write a function to convert celcius to fahrenheit like this
| one:
|
| def celciusToFahrenheit(tc):
| tf = (9/5)*tc+32
| return tf

Unless you are importing 'integer division' or using 3.0, that should be
9.0/5.0.

| I want the answer correct to one decimal place, so
| celciusToFahrenheit(12) would return 53.6.

As written, running above on 2.x returns 44.

tjr

Feb 25 '08 #7
On Feb 26, 7:14 am, "Terry Reedy" <tjre...@udel.eduwrote:
<helen.m.fl...@gmail.comwrote in message

news:d4**********************************@z17g2000 hsg.googlegroups.com...
| Hi I'm very much a beginner with Python.
| I want to write a function to convert celcius to fahrenheit like this
| one:
|
| def celciusToFahrenheit(tc):
| tf = (9/5)*tc+32
| return tf

Unless you are importing 'integer division' or using 3.0, that should be
9.0/5.0.
Has the syntax changed? I thought it was:
from __future__ import division

The OP may wish to avoid the confusion and the pointless division by
using:
tf = 1.8 * tc + 32

>
| I want the answer correct to one decimal place, so
| celciusToFahrenheit(12) would return 53.6.

As written, running above on 2.x returns 44.

tjr
Feb 25 '08 #8
On Mar 7, 5:12*pm, Piet van Oostrum <p...@cs.uu.nlwrote:
Python just uses the C library for printing, I presume, and the conversion
routines in the C library are rather simplistic. It is, however, possible
to do better, so that 53.6 -- although internally represented as something
that could be described as 53.600000000000001 -- will actually be printed
as 53.6.
There are issues with doing this portably and reliably. See

http://bugs.python.org/issue1580

for a recent discussion.

Mark
Mar 8 '08 #9
On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
Sorry to come in so late in this discussion. Although it is correct to
say that many real numbers that have an exact decimal representation
cannot be exactly represented in binary, that is no excuse to print 53.6
as 53.600000000000001. This is just lousy printing and the fact that
this kind of question comes up every week shows that it is confusing to
many people.
Good. That's a feature, not a bug.

Floats *are* confusing and unintuitive. Anyone with pretensions to be a
programmer should get over the illusion that floats are reals as soon as
possible, before they learn bad habits that have to be unlearned. If that
starts with them asking why they get 53.600000000000001 instead of 53.6,
so be it. If they want to be insulated from the harsh reality, they can
do this:
>>print 53.6
53.6

--
Steven
Mar 8 '08 #10
On Mar 7, 11:23*pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
Sorry to come in so late in this discussion. Although it is correct to
say that many real numbers that have an exact decimal representation
cannot be exactly represented in binary, that is no excuse to print 53.6
as 53.600000000000001. This is just lousy printing and the fact that
this kind of question comes up every week shows that it is confusing to
many people.

Good. That's a feature, not a bug.
Even so, it's not clear that Python's current behaviour couldn't be
improved. I have a mild dislike of the lack of consistency in the
following, which arises from Python arbitrarily stripping trailing
zeros from the result returned by the C library functions:
>>10.1
10.1
>>10.2
10.199999999999999
>>10.3
10.300000000000001
>>10.4
10.4

Piet van Oostrum's suggestion gives one nice way of dealing with
this inconsistency. Unfortunately it doesn't look easy to
implement this in practice: the main difficulty seems to be
that to ensure float(repr(x))==x round-tripping you'd
need to write routines to take control of both str -float and
float -str conversions, not forgetting that those routines
have to be reasonably fast, and work correctly on various
non IEEE 754 platforms as well as the usual ones. This means
adding, maintaining and testing hundreds of lines of
complicated code, where right now a few C library calls suffice.

Mark
Mar 8 '08 #11
On Mar 8, 11:34*am, Mark Dickinson <dicki...@gmail.comwrote:
following, which arises from Python arbitrarily stripping trailing
zeros from the result returned by the C library functions:
Correction: on closer examination it's not Python doing the
stripping of trailing zeros; it's the C library.

Mark
Mar 8 '08 #12
Mark Dickinson schreef:
On Mar 7, 11:23 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
>On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
>>Sorry to come in so late in this discussion. Although it is correct to
say that many real numbers that have an exact decimal representation
cannot be exactly represented in binary, that is no excuse to print 53.6
as 53.600000000000001. This is just lousy printing and the fact that
this kind of question comes up every week shows that it is confusing to
many people.
Good. That's a feature, not a bug.

Even so, it's not clear that Python's current behaviour couldn't be
improved. I have a mild dislike of the lack of consistency in the
following, which arises from Python arbitrarily stripping trailing
zeros from the result returned by the C library functions:
>>>10.1
10.1
>>>10.2
10.199999999999999
>>>10.3
10.300000000000001
>>>10.4
10.4
Actually I don't see what all the fuss is about. If you want a nicely
rounded number, use print or str() or the % operator.

*Only* when you use repr() or when the interactive interpreter uses it
to print the value of the expression, you get something that doesn't
look as nice.

--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
-- Isaac Asimov

Roel Schroeven
Mar 8 '08 #13
>>>>Dennis Lee Bieber <wl*****@ix.netcom.com(DLB) wrote:
>DLBOn Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum <pi**@cs.uu.nl>
DLBdeclaimed the following in comp.lang.python:
>>Sorry to come in so late in this discussion. Although it is correct to say
that many real numbers that have an exact decimal representation cannot be
exactly represented in binary, that is no excuse to print 53.6 as
53.600000000000001. This is just lousy printing and the fact that this kind
of question comes up every week shows that it is confusing to many people.

53.6
DLB53.600000000000001
>>>>print 53.6
DLB53.6
>>>>print str(53.6)
DLB53.6
>>>>print repr(53.6)
DLB53.600000000000001
>>>>>
>DLB Looks like "print" already does what you expect.
No, what you see is not the behaviour of `print' but of `str'. `print' uses
`str' to do the formatting instead of `repr' whereas the interactive prompt
uses `str'. `str' is meant to please the human reader, and `repr' is
supposed to give you something that you can use as input and get exactly
the same value. But `str' does it by just giving you less accuracy, thus
sweeping the problem under the carpet:
>>str(53.59999999999)
53.6
>>53.59999999999==53.6
False
>>repr(53.59999999999)
'53.599999999989997'
>>53.599999999989997==53.59999999999
True
>>repr(53.6)
'53.600000000000001'
>>53.600000000000001==53.6
True

--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: pi**@vanoostrum.org
Mar 10 '08 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: kdlittle88 | last post by:
Does anyone have any sample code on how to round off a float to x digits? say for example rounding 3.1415 to 3.1? Any help would be appreciated. I am learning C++ and have not found this info...
5
by: lamthierry | last post by:
Are the following two similar? float a = 1.0f; float a = static_cast<float>(1.0); If they are, which one is preferrable? Thanks Thierry
14
by: ziller | last post by:
Why is it that FLT_DIG (from <float.h>) is 6 while DBL_DIB is 15? Doing the math, the mantissa for floats is 24 bits = 2^24-1 max value = 16,777,215.0f. Anything 8-digit odd # greater than that...
6
by: karthi | last post by:
hi, I need user defined function that converts string to float in c. since the library function atof and strtod occupies large space in my processor memory I can't use it in my code. regards,...
8
by: abdul_n_khan | last post by:
Hello, I have a basic question related to datatypes. I am trying to read a value using Microsoft's ADO recordset from a field (lets call it 'Price') with datatype decimal(19,6) => 19 = Precision,...
12
by: 6tc1 | last post by:
Hi all, I just discovered a rounding error that occurs in C#. I'm sure this is an old issue, but it is new to me and resulted in a fair amount of time trying to track down the issue. Basically...
19
by: morc | last post by:
hey, I have float values that look something like this when they are printed: 6.0E-4 7.0E-4 I don't want them to be like this I want them to be normalized with 4 decimal places.
116
by: Dilip | last post by:
Recently in our code, I ran into a situation where were stuffing a float inside a double. The precision was extended automatically because of that. To make a long story short, this caused...
13
by: Shirsoft | last post by:
I have a 32 bit intel and 64 bit AMD machine. There is a rounding error in the 8th digit. Unfortunately because of the algorithm we use, the errors percolate into higher digits. C++ code is...
2
by: Mike | last post by:
I'm running DB2 v7 for z/OS. When I use SPUFI, SELECT CAST(6.0 AS FLOAT)/CAST(10.0 AS FLOAT) FROM SYSIBM.SYSDUMMY1 returns 0.6000000000000000E+00. When I use DSNTIAUL,DSNTEP2, or DSNALI (call...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.