validation for float input

Chris Barker wrote:

Again, I think the behaviour of math.frexp is going to be
system/compiler/mathlib dependent. With Python 2.3 on Linux:

You are probably right, I do not know. It is working
nicely on my win98 platform.

I still think explicitly testing for +Inf, -Inf and NaN may be the only
way, and that makes it explicit how you are handling those values, which
may, in fact, be valid for a given application.

You may not believe this:
Again on my win platform, you method returns False for 1 and -1 !!!

Anyway, I tested the fpconst mudule. It is working fine here.

Jean-Michel Fauth, Switzerland

Jean-Michel Fauth wrote:

You are probably right, I do not know. It is working
nicely on my win98 platform.

I'm kind of a platform independent fanatic...

You may not believe this:
Again on my win platform, you method returns False for 1 and -1 !!!

which method is that? I did find that:

  float("NaN") == 1.0

returns true, oddly enough, so you can't explicitly test for NaN. Both the enclosed methods seem to work for me.

Anyway, I tested the fpconst mudule. It is working fine here.

what's the fpconst module?

-Chris

import math
PlusInf = 1e1000
MinusInf = -1e1000
NotANumber = PlusInf / MinusInf

#Invalid = [PlusInf, MinusInf, NotANumber]

Invalid = [PlusInf, MinusInf]

def IsFloat1(s):
      try:
          x = float(s)
          if x in Invalid:
              return False
          else:
              return True
      except ValueError:
           return False
IsFloat1.name = "compare with IEEE values method"

def IsFloat2(s):
     try:
         x = float(s)
         return x == 0.0 or 0.0 != math.frexp(x)[0]
     except (ValueError, OverflowError):
         return False # ValueError either from the float or frexp
IsFloat2.name = "math.frexp method"

tests = ["1","-1","34.54", "23e12", "456", "34.56th", "23e999999", "-23e93893873","NaN"]

for testfun in [IsFloat1, IsFloat2]:
     print
     print "Trying test function:", testfun.name
     for s in tests:
         if testfun(s):
             print s, "Is a valid Float"
         else:
             print s, "Is NOT a valid Float"

ยทยทยท

--
Christopher Barker, Ph.D.
Oceanographer
                                         
NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Chris.Barker@noaa.gov