smallest float number

jepler at unpythonic.net jepler at unpythonic.net
Wed Feb 12 19:53:17 EST 2003


You may want to avoid the question entirely.  Python has a builtin min()
function, so if you want to find the biggest item of a group, you simply
write
	biggest = max(seq)
no need to write a loop like
	biggest_yet = -1e999
	for item in seq:
		if item > biggest_yet:
			biggest_yet = item
	biggest = biggest_yet

If your problem is that you have a sequence of items like
	("some name", 1.0)
then you can either wrap them in a class and define __cmp__ (or perhaps
__lt__) on them:
	class MyClass:
		def __init__(self, data):
			self.data = data
		def __cmp__(self, other):
			return cmp(self.data[1], other.data[1])

Or, you could use 'decorate-max-undecorate', a variation on
'decorate-sort-undecorate' (DSU):
	def decorate(item):
		return (item[1], item)
	def undecorate(decorated_item):
		return decorated_item[1]

	biggest = undecorate(min([decorate(item) for item in seq]))
I believe that you could use a generator instead of the list comprehension
if you're worried about the space required for the temporary list.
			
All that said, the most negative float number may vary.  You can construct
the most negative number fairly easily, though:
	def calculate_most_negative_float():
		i = j = -1.0
		while 1:
			j = i * 2
			if not j < i:
				break
			i = j
		return i

>>> calculate_most_negative_float()
-inf

you may also be able to get it more simply:
>>> float("-inf")
-inf

Note that the HUGE_VAL defined in C header files on my system is described
by comment as "positive infinity":
/* IEEE positive infinity (-HUGE_VAL is negative infinity).  */

#if __GNUC_PREREQ(2,96)
# define HUGE_VAL       (__extension__ 0x1.0p2047)
#else
# define __HUGE_VAL_bytes       { 0, 0, 0, 0, 0, 0, 0xf0, 0x7f }

You could load *that* value using struct.unpack() in Python.

Jeff





More information about the Python-list mailing list