472,371 Members | 1,470 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Decimals not equalling themselves (e.g. 0.2 = 0.2000000001)

I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).

However, with some, but not all, decimals, they do not seem to 'equal
themselves'. This is probably a bad way of expressing what I mean, so
I'll give an example:
>>0.5
0.5
>>0.25
0.25
>>0.125
0.125
>>0.2
0.20000000000000001
>>0.33
0.33000000000000002

As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
Aug 3 '08 #1
12 1988
CNiall schrieb:
I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).

However, with some, but not all, decimals, they do not seem to 'equal
themselves'. This is probably a bad way of expressing what I mean, so
I'll give an example:
>>0.5
0.5
>>0.25
0.25
>>0.125
0.125
>>0.2
0.20000000000000001
>>0.33
0.33000000000000002

As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
Welcome to the wonderful world of IEEE754. Just because other languages
shield you from the gory details they still are there. Python chose to
not do that, instead showing the rounding errors introduced and making
the developer decide how to deal with these.

http://pyfaq.infogami.com/why-are-fl...-so-inaccurate

Diez

Aug 3 '08 #2
CNiall schrieb:
I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).
There is - pow.
>>from math import pow
pow(625, .25)
5
Diez
Aug 3 '08 #3
On Sun, 03 Aug 2008 16:50:22 +0200, Diez B. Roggisch <de***@nospam.web.dewrote:
CNiall schrieb:
....
> >>0.2
0.20000000000000001
....
Welcome to the wonderful world of IEEE754. Just because other languages
shield you from the gory details they still are there. Python chose to
not do that, instead showing the rounding errors introduced and making
the developer decide how to deal with these.
Which other languages try to hide how floating-point numbers behave?

The correct way of dealing with this (you probably agree) is never to
expect infinite precision from floats, and design your code/algorithms
accordingly -- never use "if f1==f2:" and so on.

Floating-point is a tricky area. Lots of programmers (including me)
know too little about it.

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se R'lyeh wgah'nagl fhtagn!
Aug 3 '08 #4
Jorgen Grahn schrieb:
On Sun, 03 Aug 2008 16:50:22 +0200, Diez B. Roggisch <de***@nospam.web.dewrote:
>CNiall schrieb:
...
>> >>0.2
0.20000000000000001
...
>Welcome to the wonderful world of IEEE754. Just because other languages
shield you from the gory details they still are there. Python chose to
not do that, instead showing the rounding errors introduced and making
the developer decide how to deal with these.

Which other languages try to hide how floating-point numbers behave?
PHP and Java, amongst others. The implicitly apply a formatting when
producing a string-representation.
The correct way of dealing with this (you probably agree) is never to
expect infinite precision from floats, and design your code/algorithms
accordingly -- never use "if f1==f2:" and so on.

Floating-point is a tricky area. Lots of programmers (including me)
know too little about it.
It sure is and I don't know too much myself. But IMHO python does
something right when making the programmer aware of the problems that
can appear.

Diez
Aug 3 '08 #5
CNiall wrote:
I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).

However, with some, but not all, decimals, they do not seem to 'equal
themselves'. This is probably a bad way of expressing what I mean, so
I'll give an example:
>>0.5
0.5
>>0.25
0.25
>>0.125
0.125
>>0.2
0.20000000000000001
>>0.33
0.33000000000000002

As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
What are they teaching in computer science classes these days?

-Larry
Aug 3 '08 #6
On Aug 3, 3:02*pm, CNiall <cni...@icedcerulean.comwrote:
I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).

However, with some, but not all, decimals, they do not seem to 'equal
themselves'. This is probably a bad way of expressing what I mean, so
I'll give an example:
*>>0.5
0.5
*>>0.25
0.25
*>>0.125
0.125
*>>0.2
0.20000000000000001
*>>0.33
0.33000000000000002

As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
You're using floating point numbers and not decimals. For the
precision of decimals use the Python standard library decimal module.

As others have noted, the accuracy issue with floating point numbers
is enshrined in their implementation at the platform level and has
nothing to do with Python.

Michael Foord
--
http://www.ironpythoninaction.com/
Aug 3 '08 #7
On Sun, 03 Aug 2008 17:30:29 -0500, Larry Bates wrote:
>As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\

What are they teaching in computer science classes these days?

I don't know about these days, but 20-odd years ago there was no
discussion of floating point accuracy in the Comp Sci classes I did at
Melbourne Uni. I did a class in computational mathematics, run by the
maths department, and it discussed a lot of issues about accuracy in
float calculations. However, if they mentioned anything about e.g. 0.2
not being exactly representable in binary, I slept through it.

Maybe that's why I failed that class. *wry grin*
--
Steven
Aug 3 '08 #8
CNiall wrote:
I am very new to Python (I started learning it just yesterday), but I
have encountered a problem.

I want to make a simple script that calculates the n-th root of a given
number (e.g. 4th root of 625--obviously five, but it's just an example
:P), and because there is no nth-root function in Python I will do this
with something like x**(1/n).

However, with some, but not all, decimals, they do not seem to 'equal
themselves'. This is probably a bad way of expressing what I mean, so
I'll give an example:
>>0.5
0.5
>>0.25
0.25
>>0.125
0.125
>>0.2
0.20000000000000001
>>0.33
0.33000000000000002

As you can see, the last two decimals are very slightly inaccurate.
However, it appears that when n in 1/n is a power of two, the decimal
does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
As everyone else has pointed out, this is likely to be a
'floating point' error. what they don't mention is that you
don't actually have to use floating point at all.

For example, some numbers, m, can be represented as the product of
rational powers of primes. Its not that easy to add and subtract
them, but multiplication, division, raising to the nth power and
taking the nth root, are all easy. (m and n positive integers).

There certainly are algorithms that will evaluate the 'fourth
root of 625' as precisely 5.

More generally, there are algorithms that will guarantee to return
either
+ the exact answer as a float (if it is one)
+ the nearest or second nearest float to the actual answer
depending on your choice of:
- round towards zero
- round away from zero
- round towards positive infinity
- round towards negative infinity
- round depending on parity of next digit

It is the representation of the numbers during the intermediate
stages that is critical. You trade-off speed against accuracy.

You may well find, if you do this, that the results returned
by built-in mathematical functions DO NOT return either the
nearest or the second nearest float to the actual answer. It
depends on the underlying C library that was used, and its
programmers' choices.

So your home-rolled 'nth power' function would add a little
something to the standard functionality of the language,
and writing it would add to your understanding of the
language too.


Aug 4 '08 #9
En Sun, 03 Aug 2008 19:57:10 -0300, Grant Edwards <gr****@visi.com>
escribi�:
On 2008-08-03, Larry Bates <la*********@websafe.com`wrote:
>>
What are they teaching in computer science classes these days?

When I was an undergrad the only courses that dealt with FP
issues were classes on numerical analysis. I don't even know
if numerical analysis classes were required for CS majors. I
think most of us in that class were engineering majors.
And even if those topics were always covered in CS classes, a CS degree
isn't required to program in Python - fortunately.

--
Gabriel Genellina

Aug 5 '08 #10
On Aug 5, 3:26*pm, "Gabriel Genellina" <gagsl-...@yahoo.com.arwrote:
En Sun, 03 Aug 2008 19:57:10 -0300, Grant Edwards <gra...@visi.com*
escribi :
On 2008-08-03, Larry Bates <larry.ba...@websafe.com`wrote:
What are they teaching in computer science classes these days?
When I was an undergrad the only courses that dealt with FP
issues were classes on numerical analysis. *I don't even know
if numerical analysis classes were required for CS majors. *I
think most of us in that class were engineering majors.

And even if those topics were always covered in CS classes, a CS degree *
isn't required to program in Python - fortunately.
I had a class today which dealt with Decimal <-IEE754 conversion,
and
whilst 0.1 was an example that was converted, and a representation was
generated, no mention was made of the precision issue.

I'm hoping that it was just that we ran out of time, and the lecturer
will discuss it in detail next time.

Matt.

Aug 5 '08 #11
En Tue, 05 Aug 2008 11:50:43 -0300, schinckel <ma**@schinckel.netescribió:
I had a class today which dealt with Decimal <-IEE754 conversion,
and
whilst 0.1 was an example that was converted, and a representation was
generated, no mention was made of the precision issue.

I'm hoping that it was just that we ran out of time, and the lecturer
will discuss it in detail next time.
Presumably you encountered that 0.1 (decimal) = 0.000110011001100... (binary), and as you can see it has infinite periodic bits. IEEE754 stores only a finite number of bits for the mantissa, all the remaining (infinite) bits are dropped; a representation error is unavoidable.

--
Gabriel Genellina

Aug 5 '08 #12
On 3 Aug, 15:02, CNiall <cni...@icedcerulean.comwrote:
However, with some, but not all, decimals, they do not seem to 'equal
themselves'.
Back in my days studying electrical engineering I was pointed to this
reference about floating point arithmetic - http://citeseer.ist.psu.edu/goldberg91what.html

HTH,
Dave
Aug 5 '08 #13

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

Similar topics

3
by: Oswald | last post by:
Hey, how can I set the number of decimals? Example: 5 decimals 2.12345 2 decimals 2.12 I've found something about NumberFormat in the API, but without an example I can't solve this...
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...
2
by: westjon64 | last post by:
i am fairly new to c++, i need to know how to make it so you can input decimals into a file using the cin >> a command instead of just being able to input whole numbers and also how to make it so...
6
by: Donal McWeeney | last post by:
Hi, Is there a way to specify on the predefined format strings like P and N that you want displayed all the decimals in the number... for example 3 will display 3 2.1 will display 2.1...
13
by: vsts2007 | last post by:
hi, how can I change the number of decimals appeared in access reports... I put a formula in query and its giving three to four decimals in the output of report. I want to change the number of...
0
by: Edwin.Madari | last post by:
for nth square root: use math.sqrt n times for example ... num = math.sqrt(num) ... 5.0 all comparisons work fine for arbitrary floating point numbers... For readability print them with...
0
by: Tommy Nordgren | last post by:
On 3 aug 2008, at 17.16, Edwin.Madari@VerizonWireless.com wrote: Ehum. The OP wants to compute the nth root ( not the nth square root) ------ What is a woman that you forsake her, and the...
38
by: ssecorp | last post by:
char* reverse(char* str) { int length = strlen(str); char* acc; int i; for (i=0; i<=length-1; i++){ acc = str; } return acc; }
8
by: =?Utf-8?B?a2FyaW0=?= | last post by:
Hello All, why is this code is not showing the result in this format: 0.00 and showing it as only 0 Private Sub btn1_Click Debug.Print(Format$(Rnd() * 100, "0.00")) Dim d As Double =...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.