943,584 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 1789
  • Python RSS
Sep 14th, 2009
0

Extracting decimals

Expand Post »
I am writing a function to extract decimals from a number. Ignore the exception and its syntax, I am working on 2.5.2 (default Leopard version). My function does not yet handle 0's. My issue is, the function produces random errors with certain numbers, and I don't understand the reason. I will post an error readout after the code.

Function:
def extractDecimals(num):
	try:
		if(num > int(num)):
			decimals = num - int(num)
			while(decimals > int(decimals)):
				print 'decimal: ' + str(decimals)
				print 'int: ' + str(int(decimals))
				decimals *= 10
			decimals = int(decimals)
			return decimals
		else:
			raise DecimalError(num)
	except DecimalError, e:
		e.printErrorMessage()

Exception Class:
class DecimalError(Exception):
	def __init__(self, value):
		self.value = value
	
	def printErrorMessage(self):
		print 'The number, ' + str(self.value) + ', is not a decimal.'

Here is error output when I input the number 1.988:
decimal: 0.988
int: 0
decimal: 9.88
int: 9
decimal: 98.8
int: 98
decimal: 988.0
int: 987
decimal: 9880.0
int: 9879
decimal: 98800.0
int: 98799
decimal: 988000.0
int: 987999
decimal: 9880000.0
int: 9879999
decimal: 98800000.0
int: 98799999
decimal: 988000000.0
int: 987999999
decimal: 9880000000.0
int: 9879999999
decimal: 98800000000.0
int: 98799999999
decimal: 988000000000.0
int: 987999999999
decimal: 9.88e+12
int: 9879999999999
decimal: 9.88e+13
int: 98799999999999
decimal: 9.88e+14
int: 987999999999999
9879999999999998

I really have no idea why this is happening. Hopefully more experienced eyes will help. Thanks.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
dbmikus is offline Offline
3 posts
since Sep 2009
Sep 15th, 2009
0

Re: Extracting decimals

The reason is that you can't represent all numbers exact with floating point objects. You have to approximate the number because you have a limited number of bits. The str() function does some pretty printing of float numbers (that includes some rounding). If you print the exponential version you see what happens.

Look at the following code

python Syntax (Toggle Plain Text)
  1. def extractDecimals(num):
  2. try:
  3. if(num > int(num)):
  4. decimals = num - int(num)
  5. while(decimals > int(decimals)):
  6. print 'decimal: ' + str(decimals), '%.20e' % decimals
  7. print 'int: ' + str(int(decimals))
  8. if int(decimals)!=int(decimals+EPSILON):
  9. decimals += EPSILON
  10. break
  11. decimals *= 10
  12. decimals = int(decimals)
  13. return decimals
  14. else:
  15. raise DecimalError(num)
  16. except DecimalError, e:
  17. e.printErrorMessage()

The output for the number 1.988 is
Python Syntax (Toggle Plain Text)
  1. decimal: 0.988 9.87999999999999990000e-001
  2. int: 0
  3. decimal: 9.88 9.87999999999999900000e+000
  4. int: 9
  5. decimal: 98.8 9.87999999999999830000e+001
  6. int: 98
  7. decimal: 988.0 9.87999999999999770000e+002
  8. int: 987
  9. Result: 988

You have to determine if the number after the decimal point is close to 1.0. The number 0.9999999999999.... is mathematically equal to 1.0.
That is why I use an EPSILON value of 1E-10
Reputation Points: 38
Solved Threads: 18
Light Poster
djidjadji is offline Offline
28 posts
since Aug 2009
Sep 15th, 2009
1

Re: Extracting decimals

For exactness, use the decimal class. My take on the program using decimal. Note that decimal.Decimal is imported as "dec" to avoid confusion with the variable names. Also, I am not a decimal class expert and so use divmod to get the integer and remainder/decimal portions of a number. There are probably other ways, some of which may be better. Finally, using the decimal class is much slower than floats but is not noticeable for the normal type operations.
Python Syntax (Toggle Plain Text)
  1. from decimal import Decimal as dec
  2.  
  3. def extractDecimals(num):
  4. """ the variable 'num' is expected to be a decimal.Decimal
  5. """
  6. try:
  7. whole, remainder = divmod(num, 1)
  8. print "whole =", whole, " remainder =", remainder
  9. if remainder > 0:
  10. decimals = num - whole
  11. ctr = 0
  12. while (decimals > whole) and (ctr < 100):
  13. ctr += 1
  14. decimals *= 10
  15. whole, remainder = divmod(decimals, 1)
  16. print 'decimal: ' + str(decimals),
  17. print ' int: ' + str(whole)
  18. return int(decimals)
  19. else:
  20. raise DecimalError(num)
  21. except DecimalError, e:
  22. e.printErrorMessage()
  23.  
  24. extractDecimals(dec("0.988"))
Last edited by woooee; Sep 15th, 2009 at 5:03 pm.
Reputation Points: 741
Solved Threads: 691
Nearly a Posting Maven
woooee is offline Offline
2,302 posts
since Dec 2006
Sep 17th, 2009
0

Re: Extracting decimals

Why not using a string operation

python Syntax (Toggle Plain Text)
  1. def extractDecimals(num):
  2. return int(str(float(num)).split('.')[1])
Reputation Points: 38
Solved Threads: 18
Light Poster
djidjadji is offline Offline
28 posts
since Aug 2009
Sep 17th, 2009
0

Re: Extracting decimals

Thanks for the help everyone. As to why I am not using better built in methods: I am not doing this code to complete a further goal. I am doing things the hard way so I can become a better programmer. If I wanted a fast efficient method to be put to use in other software, I would use something that has already been made for me. Thanks for the help.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
dbmikus is offline Offline
3 posts
since Sep 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Recursive Fibonacci
Next Thread in Python Forum Timeline: Paint with Python-Pygame





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC