473,651 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.2000000000000 0001
>>0.33
0.3300000000000 0002

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.2000000000000 0001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
Aug 3 '08 #1
12 2089
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.2000000000000 0001
>>0.33
0.3300000000000 0002

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.2000000000000 0001?

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.w eb.dewrote:
CNiall schrieb:
....
> >>0.2
0.200000000000 00001
....
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.w eb.dewrote:
>CNiall schrieb:
...
>> >>0.2
0.20000000000 000001
...
>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.2000000000000 0001
>>0.33
0.3300000000000 0002

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.2000000000000 0001?

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...@icedcer ulean.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.2000000000000 0001
*>>0.33
0.3300000000000 0002

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.2000000000000 0001?

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.2000000000000 0001?

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.2000000000000 0001
>>0.33
0.3300000000000 0002

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.2000000000000 0001?

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.co m>
escribi�:
On 2008-08-03, Larry Bates <la*********@we bsafe.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

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

Similar topics

3
5636
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
51022
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 field is float. The datatype for the other fields are int. I have tried testing by dividing 7 by 10000, which should give me 0.0007. The result in the database is 0.
2
2214
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 that it outputs decimals and not just rounded off whole numbers
6
2607
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 3.21 will display 3.21
13
3034
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 decimals to zero. can anybody guide me in this .
0
1038
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 required precision. for example True (0.20000000000000001, 0.20000000000000001) ('0.20', '0.20')
0
1110
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 hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women
38
2702
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
3279
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 = Math.Round(2250.0, 3) txt2.Text = txt1.Text \ d
0
8352
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
8275
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
8802
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8465
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,...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5612
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();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4283
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1587
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.