By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,689 Members | 1,101 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,689 IT Pros & Developers. It's quick & easy.

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

P: n/a

On 3 aug 2008, at 17.16, Ed********** wrote:
for nth square root: use math.sqrt n times for example
Ehum. The OP wants to compute the nth root ( not the nth square root)
>>>import math
num = 625
how_many_sqrt = 2
for i in range(how_many_sqrt):
.. num = math.sqrt(num)

all comparisons work fine for arbitrary floating point numbers...
For readability print them with required precision. for example
>>>a = .2
b = .4
b = b/2
a == b
>>>a, b
(0.20000000000000001, 0.20000000000000001)
>>>'%.2f' % a, '%.2f' % b
('0.20', '0.20')

thx. Edwin

-----Original Message-----
From: py************************************************ **
[mailto:py***************************************** *********
On Behalf Of CNiall
Sent: Sunday, August 03, 2008 10:03 AM
To: py*********
Subject: 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
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
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:

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
and not 0.20000000000000001?

This discrepancy is very minor, but it makes the whole n-th root
calculator inaccurate. :\
The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure. If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof. Thank you.
What is a woman that you forsake her, and the hearth fire and the home
to go with the old grey Widow Maker. --Kipling, harp song of the Dane
Tommy Nordgren

Aug 3 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.