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.

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

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

The output for the number 1.988 is

decimal: 0.988 9.87999999999999990000e-001
int: 0
decimal: 9.88 9.87999999999999900000e+000
int: 9
decimal: 98.8 9.87999999999999830000e+001
int: 98
decimal: 988.0 9.87999999999999770000e+002
int: 987
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

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.

from decimal import Decimal as dec

def extractDecimals(num):
   """ the variable 'num' is expected to be a decimal.Decimal
   """
   try:
      whole, remainder = divmod(num, 1)
      print "whole =", whole, "  remainder =", remainder
      if remainder > 0:
         decimals = num - whole
         ctr = 0
         while (decimals > whole) and (ctr < 100):
            ctr += 1
            decimals *= 10
            whole, remainder = divmod(decimals, 1)
            print 'decimal: ' + str(decimals),
            print '     int: ' + str(whole)
         return int(decimals)
      else:
         raise DecimalError(num)
   except DecimalError, e:
      e.printErrorMessage()

extractDecimals(dec("0.988"))
commented: good point +8

Why not using a string operation

def extractDecimals(num):
    return int(str(float(num)).split('.')[1])

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.