[Tutor] Need a better name for this function
Richard D. Moores
rdmoores at gmail.com
Thu Dec 17 16:40:11 CET 2009
On Thu, Dec 17, 2009 at 02:13, Dave Angel <davea at ieee.org> wrote:
> Try the following in Python 3.1:
>
> def increment(floatval, incr=1):
> #Given a float of "reasonable" size, increment it by smallest amount
> # and if incr is -1, then decrement
> stringval = floatval.hex()
> mantissa, exponent = stringval.split("p")
> mantissa = mantissa.replace(".", "") #ignore the period
> mantissa = hex(int(mantissa, 16) + incr)
> newstringval = mantissa[:3] + "." + mantissa[3:] + "p" + exponent
> newfloatval = float.fromhex(newstringval)
> #print(floatval, newstringval, newfloatval)
> return newfloatval
>
>
> You can specify an increment of +1 or -1, but larger values also work just
> as well. From limited testing, this works for any positive values that
> aren't in the gradual underflow range.
>
> The parsing and reassembly of the mantissa and exponent are pretty sloppy,
> but maybe they are even correct, for the output of the hex() method.
>
> DaveA
Thanks very much Dave. Enlightening.
Dick
More information about the Tutor
mailing list