473,786 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Math errors in python

In python 2.3 (IDLE 1.0.3) running under windows 95, I get the
following types of errors whenever I do simple arithmetic:

1st example:
12.10 + 8.30 20.399999999999 999 1.1 - 0.2 0.9000000000000 0013
2nd example(no errors here): bool(130.0 - 129.0 == 1.0) True
3rd example: a = 0.013
b = 0.0129
c = 0.0001
[a, b, c] [0.0129999999999 99999, 0.0129, 0.0001] bool((a - b) == c)

False
This sort of error is no big deal in most cases, but I'm sure it could
become a problem under certain conditions, particularly the 3rd
example, where I'm using truth testing. The same results occur in all
cases whether I define variables a, b, and c, or enter the values
directly into the bool statement. Also, it doesn't make a difference
whether "a = 0.013" or "a = 0.0130".

I haven't checked this under windows 2000 or XP, but I expect the same
thing would happen. Any suggestions for a way to fix this sort of
error?
Jul 18 '05
89 5152
Paul Rubin <http://ph****@NOSPAM.i nvalid> wrote in message news:<7x******* *****@ruckus.br ouhaha.com>...
Gary Herron <gh*****@island training.com> writes:
Any representation of the infinity of numbers on a finite computer
*must* necessarily be unable to represent some (actually infinity
many) of those numbers. The inaccuracies stem from that fact.
Well, finite computers can't even represent all the integers, but
we can reasonably think of Python as capable of doing exact integer
arithmetic.

The issue here is that Python's behavior confuses the hell out of some
new users. There is a separate area of confusion, that

a = 2 / 3

sets a to 0,


That may confusing for non-C programmers, but it's easy to explain.
The real flaw of old-style division is that code like

def mean(seq):
return sum(seq) / len(seq)

subtly fails when seq happens to contain all integers, and you can't
even correctly use:

def mean(seq):
return 1.0 * sum(seq) / len(seq)

because it could lose accuracy if seq's elements were of a custom
high-precision numeric type that is closed under integer division but
gets coerced to float when multiplied by a float.
That doesn't solve the also very
common confusion that (1.0/3.0)*3.0 = 0.99999999.
What problem?
(1.0 / 3.0) * 3.0

1.0

The rounding error of multiplying 1/3 by 3 happens to exactly cancel
out that of dividing 1 by 3. It's an accident, but you can use it as
a quick argument against the "decimal arithmetic is always more
acurate" crowd.
Rational arithmetic can solve that.


Yes, it can, and imho it would be a good idea to use rational
arithmetic as the default for integer division (but _not_ as a general
replacement for float).
Jul 18 '05 #51
the problem with BCD or other 'decimal' computations is that it either
doesn't have the dynamic range of binary floating point (~ +-10**310)
or if it has unlimited digits then there is a LOT of software cranking
to do the math, whereas binary floating point is in the hardware. If
you want the language to use binary floating point (fast) but do the
rounding for you, then fine, but then you will have problems using it
for any real numerical task because the issue of rounding is very
important to numerical analysis, and is done different ways in
different cases. Every time the language runtime rounds for you, it is
introducing errors to your computations that you may or may not want.
There is a large body of knowledge surrounding the use of IEEE 754
floating point representation and if the language diverges from that
then users who want to do numerical analysis won't use it.

another question: do you want the math package to round for you, or do
you want the IO package to do it only when you print? You will get
different results from each. I could imagine a language runtime could
have a switch that tells it to automatically round the results for
you, either in the math or the IO.
Jul 18 '05 #52
[Paul Rubin]
I don't know that it's generally tractable to do exact computation on
constructive reals. How do you implement comparison (<, >, ==)?


Equality of constructive reals is undecidable. In practice, CR
packages allow specifying a "number of digits of evidence " parameter
N, so that equality is taken to mean "provably don't differ by more
than a unit in the N'th digit".
Jul 18 '05 #53
[Chris S.]
Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this
arithmetic is meant for.


That's absurd. pi is 3, and nothing but grief comes from listening to
fancy-pants so-called "mathematicians " trying to convince you that
their inability to find integer results is an intellectual failing you
should share <wink>.
Jul 18 '05 #54
On Mon, 20 Sep 2004 15:16:07 +1200, Paul Foley <se*@below.inva lid> wrote:
On 19 Sep 2004 15:24:31 -0700, Dan Bishop wrote:
There are, of course, reasonably accurate rational approximations of
pi. For example, 355/113 (accurate to 6 decimal places), 312689/99532
(9 decimal places), or 3126535/995207 (11 decimal places). Also, the
IEEE 754 double-precision representation of pi is equal to the
rational number 450359962737049 6/281474976710656 .


I hope not! That's equal to 16. (The double float closest to) pi is
88427971900355 5/281474976710656

Amazingly, that is _exactly_ equal to math.pi
from ut.exactdec import ED
import math
ED('88427971900 3555/281474976710656 ') ED('3.141592653 589793115997963 468544185161590 576171875') ED(math.pi,'all ') ED('3.141592653 589793115997963 468544185161590 576171875') ED('88427971900 3555/281474976710656 ') == ED(math.pi,'all ') True
ED('88427971900 3555/281474976710656 ').astuple() (31415926535897 931159979634685 441851615905761 71875L, 1L, -48) ED(math.pi,'all ').astuple() (31415926535897 931159979634685 441851615905761 71875L, 1L, -48)

So it's also equal to the rational number
314159265358979 311599796346854 418516159057617 1875 / 10**48
ED('31415926535 897931159979634 685441851615905 76171875' ... '/100000000000000 000000000000000 000000000000000 0000')
ED('3.141592653 589793115997963 468544185161590 576171875')

or
ED('31415926535 897931159979634 685441851615905 76171875') / ED(10**48)

ED('3.141592653 589793115997963 468544185161590 576171875')

Regards,
Bengt Richter
Jul 18 '05 #55
[Bengt Richter]
...
If you add a small Decimal delta repeatedly, will it get rounded away like the
floating point version,
Decimal *is* a floating-point type, containing most of IEEE 854 (the
radix-generalized variant of IEEE 754). It's got infinities, signed
zeroes, NaNs, ..., all that FP hair. Decimal specifies unnormalized
fp, though, so there's no special class of "denormal" values in
Decimal.
or will accuracy get promoted,


No, but the number of digits of precision is user-specifiable. In all
places this makes sense, the result of an operation is the exact
(infinite precision) mathematical result, rounded once to the current
context precision, according to the current context rounding mode. If
you want 100 digits, ask for 100 digits -- but you have to ask in
advance.
Jul 18 '05 #56
On 19 Sep 2004 15:24:31 -0700, da*****@yahoo.c om (Dan Bishop) wrote:
Also, the
IEEE 754 double-precision representation of pi is equal to the
rational number 450359962737049 6/281474976710656 .
I know the real uses of a precise pi are not that many... but
isn't that a quite raw approximation ? that fraction equals 16...
Base 10 _is_ more accurate for monetary amounts, and for this reason I
agreed with the addition of a decimal class. But it would be a
mistake to use decimal arithmetic, which has a performance
disadvantage with no accuracy advantage, in the general case.


For monetary computation why not using fixed point instead
(i.e. integers representing the number of thousands of cents,
for example) ? IMO using floating point instead of something
like arbitrary precision integers is looking for trouble in
that area as often what is required is accuracy up to a
specified fraction of the unit.

Andrea

PS: From a study seems that 75.7% of people tends to believe
more in messages that contain precise numbers (like 75.7%).
Jul 18 '05 #57
On Mon, 20 Sep 2004 01:07:03 -0400, Tim Peters <ti********@gma il.com>
wrote:
[Chris S.]
Sqrt is a fair criticism, but Pi equals 22/7, exactly the form this
arithmetic is meant for.


That's absurd. pi is 3, and nothing but grief comes from listening to
fancy-pants so-called "mathematicians " trying to convince you that
their inability to find integer results is an intellectual failing you
should share <wink>.


This is from the Bible...

007:023 And he made a molten sea, ten cubits from the one brim to the
other: it was round all about, and his height was five cubits:
and a line of thirty cubits did compass it round about.

So it's clear that pi must be 3

Andrea
Jul 18 '05 #58
Uncle Tim:
That's absurd. pi is 3


Personally I've found that pie is usually round, though
if you're talking price I agree -- I can usually get a
slice for about $3, more like $3.14 with tax. I like
mine apple, with a bit of ice cream.

Strange spelling though.

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #59
Andrea:
This is from the Bible...

007:023 And he made a molten sea, ten cubits from the one brim to the
other: it was round all about, and his height was five cubits:
and a line of thirty cubits did compass it round about.

So it's clear that pi must be 3


Or that the walls were 0.25 cubits thick, if you're talking
inner diameter vs. outer. ;)

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #60

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

Similar topics

1
2080
by: TC | last post by:
I am getting small math errors when I use a query to convert a column's data type from Text to Single. I am using a calculated column with the following expression. HighSchoolGPA: IIf(IsNull(),Null,CSng()) When GPA = "3.10", HighSchoolGPA := 3.09999990463257, not 3.1. For this particular application, the difference between 3.09999990463257 and 3.1 is unacceptable.
0
9647
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9491
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10104
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4063
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.