473,394 Members | 1,870 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,394 software developers and data experts.

results of division

Hello,

What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.

Thank you,
Brad
Jul 18 '05 #1
14 1787
On Thu, 09 Dec 2004 09:38:55 -0500, Brad Tilley <br********@gmail.com> wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.


Use the new decimal type - <http://www.python.org/doc/2.4/whatsnew/node9.html>.

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 18 '05 #2
Brad Tilley <br********@gmail.com> writes:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like
precision. Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.


"%.2f"% 1.775
Jul 18 '05 #3
In article <cp**********@solaris.cc.vt.edu>,
Brad Tilley <br********@gmail.com> wrote:

What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.


You have two options: use floating point and round manually or use the
new Decimal class and specify your precision. However, if you restrict
your calculations, you will have errors after chaining more than one or
two operations. Your best bet is to perform rounding only at the end of
your calculations, at which point you can either round the result
directly or round for display only (by using appropriate % formatting).
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing." --Alan Perlis
Jul 18 '05 #4
Brad Tilley wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.


The answer is "what are you trying to do?". The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing. Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?

-Peter
Jul 18 '05 #5
"Paul Rubin" <http://ph****@NOSPAM.invalid> wrote in message
news:7x************@ruckus.brouhaha.com...
Brad Tilley <br********@gmail.com> writes:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like
precision. Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.


"%.2f"% 1.775


At the risk of kicking off *another* floating-point representation thread,
here is some odd string interp behavior (Python 2.3.4).

I seemed to recall in the past finding that the above syntax would not
round, but would instead truncate (old C runtime perhaps), so that even
printing 1.779 to 2 decimal places would print only "1.77". So I tried a
few things at the Python prompt, and got some odd behavior.
print "%.2f" % 1.776 1.78 print "%.2f" % 1.774 1.77

Good so far, now let's try the borderline case:
print "%.2f" % 1.775 1.77

Hmmm, if we rounded, I would have expected 1.775 to round up to 1.78.
Perhaps this is a floating point rep issue, that we are really rounding
1.7749999999999999999 or something. Sure enough, repr shows us:
repr(1.775) '1.7749999999999999'

So I added a wee bit to 1.775:
print "%.2f" % 1.775000000001 1.78

Ok, that looks better. What if I round explicitly?
print "%.2f" % round(1.775,2)

1.78

Errr? How come round() is able to understand 1.775 correctly, whereas
string interp is not? I'm guessing that round() adds some small epsilon to
the value to be rounded, or perhaps even does the brute force rounding I
learned in FORTRAN back in the 70's: add 0.5 and truncate. But this would
still truncate 1.779999999 to two places, so this theory fails also. What
magic is round() doing, and should this same be done in the string interp
code?

-- Paul

Jul 18 '05 #6
Simon Brunning wrote:
On Thu, 09 Dec 2004 09:38:55 -0500, Brad Tilley <br********@gmail.com> wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.

Use the new decimal type - <http://www.python.org/doc/2.4/whatsnew/node9.html>.


Ah, quantize() works great. Thank you for the tip.
Jul 18 '05 #7
Peter Hansen wrote:
Brad Tilley wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.

The answer is "what are you trying to do?". The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing. Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?

-Peter


I'm summing up the bytes in use on a hard disk drive and generating a
report that's emailed based on the percentage of the drive in use. I
know there are other ways to do this, but I like Python and I like to
write my own code. I always find comp.lang.python a very helpful place.

Thank you,

Brad
Jul 18 '05 #8
[Paul McGuire]
....
print "%.2f" % 1.775 1.77

Hmmm, if we rounded, I would have expected 1.775 to round up
to 1.78.
Platform-dependent. 1.775 isn't exactly representable regardless, but
whether exactly-half-way numbers that are exactly representable round
up or truncate varies across platform C libraries. For example, 1.25
is exactly representable in binary fp, but '%.1f' % 1.25 produces 1.3
on Windows but 1.2 on most other platforms (most non-Microsoft C
runtimes use the IEEE "round to nearest or even" rule).
Perhaps this is a floating point rep issue, that we are really
rounding 1.7749999999999999999 or something. Sure enough,
repr shows us:
repr(1.775) '1.7749999999999999'

So I added a wee bit to 1.775:
print "%.2f" % 1.775000000001 1.78

Ok, that looks better. What if I round explicitly?
print "%.2f" % round(1.775,2) 1.78

Errr? How come round() is able to understand 1.775 correctly,
whereas string interp is not? I'm guessing that round() adds
some small epsilon to the value to be rounded,
No way -- that would be insane.
or perhaps even does the brute force rounding I learned in
FORTRAN back in the 70's: add 0.5 and truncate.
Yes, that's what Python's round() does.
But this would still truncate 1.779999999 to two places, so this
theory fails also.
No:
1.775 1.7749999999999999 1.775 * 100.0 177.5 1.775*100 + 0.5 178.0


That is, before adding 0.5, it multiplies by 100.0. The vagaries of
binary fp are such that machine_value_for(1.755) * 100 is exactly
175.5, and adding 0.5 to that gives 178 exactly.
What magic is round() doing, and should this same be done in the
string interp code?


Python implements round() itself. Float string formatting is done by
the platform C sprintf(). If you care about decimal representations
so much that you can't tolerate vagaries due to differences in the
53rd significant bit, use the new decimal module instead.
Jul 18 '05 #9
Brad Tilley wrote:
Peter Hansen wrote:
The answer is "what are you trying to do?". The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing. Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?


I'm summing up the bytes in use on a hard disk drive and generating a
report that's emailed based on the percentage of the drive in use. I
know there are other ways to do this, but I like Python and I like to
write my own code. I always find comp.lang.python a very helpful place.


So, from the sounds of it, you really care about this
rounding operation in the displayed values, in which
case the "'%.2f' % value" approach ought to be fine.

-Peter
Jul 18 '05 #10
"Paul McGuire" <pt***@austin.rr._bogus_.com> writes:
Errr? How come round() is able to understand 1.775 correctly, whereas
string interp is not? I'm guessing that round() adds some small epsilon to
the value to be rounded, or perhaps even does the brute force rounding I
learned in FORTRAN back in the 70's: add 0.5 and truncate. But this would
still truncate 1.779999999 to two places, so this theory fails also. What
magic is round() doing, and should this same be done in the string interp
code?


Consulting bltinmodule.c would tell you. round(x,n) in (Python 2.4):

multiplies x by 10**n
adds .5
truncates
divides by 10**n.

Don't confuse this trick with giving us the correct result though,
it's still floating point:
round(1.77499999999999999, 2)

1.78

--
Christopher A. Craig <co********@ccraig.org>
"[Windows NT is] not about 'Where do you want to go today?'; it's more like
'Where am I allowed to go today?'" -- Mike Mitchell, NT Systems Administrator

Jul 18 '05 #11
In article <cp**********@solaris.cc.vt.edu>,
Brad Tilley <br********@gmail.com> wrote:
Brad Tilley wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do
.... I'm summing up the bytes in use on a hard disk drive and generating a
report that's emailed based on the percentage of the drive in use.


Stilling guessing a little about what you're trying to do -
probably implicitly or explicitly invoking the "repr" function
on this values (implicitly for example via repr() or str() on
a sequence of them.) So,

a = [1.775, 1.949]
print a
yields
[1.7749999999999999, 1.9490000000000001]

You will get something more like what you want with
the str() function instead. str(1.775) == '1.775'

from types import FloatType
class ClassicFloat(FloatType):
def __repr__(self):
return self.__str__()

print map(ClassicFloat, [1.775, 1.949])

yields
[1.775, 1.949]
(Seems to me the standard float type behaved like
this in Python 1.5.4, hence "classic".)

Donn Cave, do**@u.washington.edu
Jul 18 '05 #12
Brad Tilley wrote:
Hello,

What is the proper way to limit the results of division to only a few spaces after the decimal? I don't need rocket-science like precision. Here's an example:


If your only complaint is that it's ugly to display 17 digits, then use
the % operator to display however many digits you want.

print "%.3f" % x # prints 3 digits after the decimal point

If you're referring to internal calculations, then you seem to have a
misunderstanding of the way floating-point math works. Intel hardware
does all arithmetic with 64 significant bits (which get rounded to 53
when stored as "double precision"), and there's no way to tell it
"Don't bother calculating all 64 bits; I only need 11." It would take
extra code to get rid of the extra bits, and why bother slowing down
your program to make the math *less* accurate?

Jul 18 '05 #13
In article <cp**********@utornnr1pp.grouptelecom.net>,
Peter Hansen <pe***@engcorp.com> wrote:
Brad Tilley wrote:
Peter Hansen wrote:
The answer is "what are you trying to do?". The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing. Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?
I'm summing up the bytes in use on a hard disk drive and generating a
report that's emailed based on the percentage of the drive in use. I
know there are other ways to do this, but I like Python and I like to
write my own code. I always find comp.lang.python a very helpful place.


So, from the sounds of it, you really care about this

^don'trounding operation in the displayed values, in which
case the "'%.2f' % value" approach ought to be fine.


Right?
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing." --Alan Perlis
Jul 18 '05 #14
Aahz wrote:
In article <cp**********@utornnr1pp.grouptelecom.net>,
Peter Hansen <pe***@engcorp.com> wrote:
So, from the sounds of it, you really care about this


^don't
rounding operation in the displayed values, in which
case the "'%.2f' % value" approach ought to be fine.


Right?


I think what I meant to say was "you really care about
this *only* in the displayed values", but with that
"don't" in there it comes out the same in the wash. :-)

-Peter
Jul 18 '05 #15

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

Similar topics

12
by: Tim Rowe | last post by:
If I do from __future__ import division then eval(1/2) gives me 0.5 as expected. But if I do print input("enter a sum: ") and enter 1/2 as the sum I get 0 as if I hadn't done the import. I thought...
2
by: Michael Cornelius | last post by:
As an old C programmer, I'm surprised by some results I'm getting with integer division. For example: >>> -1/1000 -1 >>> -9/2 -5 I expect the results of these expressions to be 0 and -4,...
15
by: joel | last post by:
I have a table which I want to update by dividing one field into another. The update runs with no errors, but the results come out as only a positive integer number. The datatype for the result...
17
by: seb.haase | last post by:
Hi, Is it true that that "Python 3000" is dead ? Honestly I think that e.g. changing 5/2 to be 2.5 (instead of 2) would just break to much code :-( On the otherhand I'm using Python as "Matlab...
0
by: r1 | last post by:
I am relatively inexperienced in using delegates and asynchronous methods. I read several articles, and then I developed my own code with a mission to improve the performance. Wow! I cannot...
2
by: kermit | last post by:
For a long time,, There has been a discussion of trueFor division versus integer division in Python. I myslef prefer that / be used for integer division since almost always, I want the...
13
by: jamesonang | last post by:
Supposed unsigned int(32 bits) is the largest number that computer can represent with a single variable. Now, i have a big integer ( less than 64 bit, but great than 32 bit) . i represent it by...
1
by: aaronkm | last post by:
Hello thescripts and well met. I've recently been handed a new duty and have the joy of 'crash coursing' MS Access. Things are working well but I've ran into a problem that I can't seem to find...
3
by: Bigalan | last post by:
Hello, i am relatively new to PHP and i am struggling with printing multiple search results on to different pages. The code below works ok but when you click on next page button, it brings up a blank...
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...

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.