473,854 Members | 1,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to convert float to sortable integer in Python

Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!

Jan 16 '07 #1
7 6277
On Tue, 16 Jan 2007 01:21:52 -0800, shellon wrote:
Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!
Google says:

Your search - float2rawInt - did not match any documents.

Are you sure about that function? What's a sortable integer?
--
Steven.

Jan 16 '07 #2
shellon wrote:
Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!
float comparision works well enough for sorting in Python. What is
the actual requirement?

see also hash() and id() for keying.

Robert
Jan 16 '07 #3
robert <no*****@no-spam-no-spam.invalidwro te:
shellon wrote:
>Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!

float comparision works well enough for sorting in Python. What is
the actual requirement?
Maybe this is the problem?
>>sorted([-0.0, 0.0, -0.0, 0.0, -0.0])
[-0.0, 0.0, -0.0, 0.0, -0.0]

Java sorting imposes an artificial total ordering on float or double
values:
The < relation does not provide a total order on all floating-point
values; although they are distinct numbers -0.0 == 0.0 is true and a
NaN value compares neither less than, greater than, nor equal to any
floating-point value, even itself. To allow the sort to proceed,
instead of using the < relation to determine ascending numerical
order, this method uses the total order imposed by
Double.compareT o(java.lang.Dou ble). This ordering differs from the <
relation in that -0.0 is treated as less than 0.0 and NaN is
considered greater than any other floating-point value. For the
purposes of sorting, all NaN values are considered equivalent and
equal.
Jan 16 '07 #4
shellon wrote:
Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!
You should know you can sort mixed float/integer values in Python
>>l=[3,2.3,1.45,2,5]
l.sort()
l
[1.45, 2, 2.2999999999999 998, 3, 5]

to convert a float to int use the built-in int function:
>>int(2.34)
2

Hope this helps

regards

Wolfgang
Jan 16 '07 #5
I'm sorry I mistake the function name, the function is
floatToRawIntBi ts(), it convert ieee 754 floating point number to
integer, e.g. if f1>f2 then floatToRawBits( f1) floatToRawBits( f1)
I want convert floating point number to sortable string to index in
Lucene, so I want first to conver the floating point number to integer
first, and than convert the integer to sortable string?

so How to convert a ieee 754 floating point to raw bits like the java
api floatToRawBits do?

Appreciate your help!

Steven D'Aprano wrote:
On Tue, 16 Jan 2007 01:21:52 -0800, shellon wrote:
Hi all:
I want to convert the float number to sortable integer, like the
function float2rawInt() in java, but I don't know the internal
expression of float, appreciate your help!

Google says:

Your search - float2rawInt - did not match any documents.

Are you sure about that function? What's a sortable integer?
--
Steven.
Jan 17 '07 #6
shellon wrote:
I'm sorry I mistake the function name, the function is
floatToRawIntBi ts(), it convert ieee 754 floating point number to
integer, e.g. if f1>f2 then floatToRawBits( f1) floatToRawBits( f1)
You can get the raw bits of a floating point number by packing into a
string then unpacking it as an integer, but the invariant you give
doesn't hold when you do that. That is, f1>f2 does not guarantee
rawbits(f1)>raw bits(f2). So be warned.

Python floats are double-precision internally, so the integer returned
would have to hold at least 64-bits (i.e., it'd be a long on 32-bit
platforms).

import struct

def double_to_raw_i nt(d):
return struct.unpack(" =q",struct.pack ("=d",d))

I want convert floating point number to sortable string to index in
Lucene, so I want first to conver the floating point number to integer
first, and than convert the integer to sortable string?
I presume that, by "sortable string", you mean a numerical
representation (padded or something), but if all you want is a string
containing the bits of the number, struct.pack("=d ",d) will get you an
8-byte string representing the bits without having to change it to an
integer first. Check the documentation for the struct module if you
need a certain endianness.

so How to convert a ieee 754 floating point to raw bits like the java
api floatToRawBits do?
See documentation for the struct module.
Carl Banks

Jan 17 '07 #7
At Wednesday 17/1/2007 03:36, shellon wrote:
>I'm sorry I mistake the function name, the function is
floatToRawIntB its(), it convert ieee 754 floating point number to
integer, e.g. if f1>f2 then floatToRawBits( f1) floatToRawBits( f1)
I want convert floating point number to sortable string to index in
Lucene, so I want first to conver the floating point number to integer
first, and than convert the integer to sortable string?
The following two functions may be useful; they do more-or-less the
same thing, but returning a string instead of an integer.
Note that this property: f1>f2 =floatToRawBits (f1) >
floatToRawBits( f2), only holds for nonnegative numbers; this code
has the same restriction.

The code assumes a few things: float(repr(x))= =x for 0.5<=x<1 (that
is, repr(x) is exact in that range); the maximum double value has an
exponent (as given by frexp) less than 5000; the minimum positive
value has an exponent greater than -5000; 0 is the only number having
mantissa==0; and surely I'm assuming many more but I'm not aware of
them. I think it's not dependent on a particular FP hardware or representation.
Beasts like denormals, INFs and NaNs are not considered at all. It
appears to work OK for "normal" numbers, but I've not checked all
corner cases. It was only tested on Windows XP.
After such long disclaimer... I hope it's useful :)

--- begin fpsrepr.py ---
import math

def float2srepr(f):
"""Convert a floating point number into a string representation
which can be sorted lexicographical ly maintaining the original
numerical order (only for numbers >= 0).
That is, given f1,f2 >= 0, f1<f2 <=float2srepr(f 1)<float2srepr( f2)
Denormals, INFs, NaNs are not handled at all!

format: Seeeem*
S : sign, "0" for +, else "-"
eeee: exponent + 5000 (never negative)
m* : mantissa, one or more chars as needed,
0.5<=mantissa<1 , without the leading "0."
"""
try: m, e = math.frexp(f)
except ValueError,E:
E.args = list(E.args) + [repr(f)]
raise
if m < 0:
sign = '-'
m = -m
else:
sign = '0'
e = e+5000
if m==0.0: e = 0
return "%s%04.4d%s " % (sign, e, repr(m)[2:])

def srepr2float(s):
"""Convert a string in the format used by float2srepr
into a floating point number.
srepr2float(flo at2srepr(x)) == x
"""
sign, e, m = s[0], s[1:5], s[5:]
neg = sign == '-'
e = int(e)
e = e-5000
m = float('0.'+m)
if m==0: f = 0
else: f = math.ldexp(m, e)
if neg: f = -f
return f

# test

def find_eps(): # smallest x such 1+x!=1
prev, curr = 1.0, 0.5
while 1.0+curr 1.0 and curr < prev:
prev = curr
curr /= 2.0
return prev

def find_minf(): # smallest x such x>0
prev, curr = 1.0, 0.5
while curr 0.0 and curr < prev:
prev = curr
curr /= 2
return prev

eps = find_eps()
print "eps=%r %r" % (eps, 1.0+eps)
minf = find_minf()
print "minf=%r %r" % (minf, -minf)

values = [0,0.1,0.2,0.3,0 .4,0.5,0.6,0.7, 0.8,0.9,
1.0,1.0+eps,1.0 +2*eps,1.0-eps,1.0-2*eps,
2,3,10,10.00000 01,10.000000000 01,
123.456,1234.56 7,12345.678,123 456.789,1.234e1 0,
123412341234,12 341234123412341 2341234.0,1.234 e20,
1e100,1e200,1e3 00,math.pi,math .e]
values += [1.0/x for x in values if x>0] + [eps, minf]
values += [-x for x in values]
values = sorted(values)
for x in values:
s = float2srepr(x)
xr = srepr2float(s)
print '%-30r %s' % (x, s)
assert x==xr, '%r!=%r' % (x, xr)

f2svalues = [float2srepr(x) for x in values if x>=0]
s2fvalues = [srepr2float(x) for x in sorted(f2svalue s)]
assert s2fvalues == sorted(s2fvalue s), s2fvalues
--- end fpsrepr.py ---
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 17 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
9822
by: franzkowiak | last post by:
Hello, I've read some bytes from a file and just now I can't interpret 4 bytes in this dates like a real value. An extract from my program def l32(c): return ord(c) + (ord(c)<<8) + (ord(c)<<16) + (ord(c)<<24)
1
3119
by: Bell, Kevin | last post by:
I'm pulling a range of cells from Excel into a list and the data in Excel is a number or possibly some text like an asterisk. Each member of the list is a com object (I think) and I'm converting them to integers (or to None if not numberic) but my method seems very silly. Is this the best way to go about it? It does exactly what it should, but it seems like a lot of extra BS to convert my object to a string to a float to a rounded...
13
41837
by: Hako | last post by:
I try this command: >>> import string >>> string.atoi('78',16) 120 this is 120 not 4E. Someone can tell me how to convert a decimal number to hex number? Can print A, B, C,DEF. Thank you.
3
2547
by: David Lozzi | last post by:
Howdy, ISSUE 1: See issue 2 below. I have a distance calculator on my site which works great. However, the users need to sort by distance, which make sense. I'm not sure how to do it other than like this. With the returning query include the distance from origin. Here's my dilemma, I have the script working great in VB which provides the distance, but that is not sortable, but when I port it over to TSQL I get differing results. Here is the...
11
15207
by: redefined.horizons | last post by:
I'm still pretty new to Python. I'm writing a function that accepts thre integers as arguments. I need to divide the first integer by te second integer, and get a float as a result. I don't want the caller of the function to have to pass floats instead of integers. How do I convert the arguments passed to the function into floats before I do the division? Is this necessary, or is their a better way? Thanks, Scott Huey
10
107688
by: yinglcs | last post by:
Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, i1)' always return 0, can you please tell me how can i convert it from an integer to float? def compareValue(n1, n2): i1 = int(n1) i2 = int(n2) dx = abs(i2 - i1)/min(i2, i1)
2
817
by: ireyes | last post by:
DEAR SIR, I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE. CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION? DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT? REGARDS AND THANKS A LOT IVAN REYES ___________________________________
7
4609
by: Guido van Brakel | last post by:
Hello I have this now: It now gives a int, but i would like to see floats. How can integrate that into the function? Regards,
0
9751
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11025
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10758
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9513
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7915
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7082
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4562
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.