473,795 Members | 2,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit twiddling floating point numbers

Hi All

Is there a simple way to twiddle the bits of a float? In particular, I
would like to round my float to the n most significant bits.

For example - 0.123 in binary is 0.000111111
Rounding to 4 bits I get 0.0001.

I can pack and unpack a float into a long
e.g.
struct.unpack(' I',struct.pack( 'f',0.123))[0]
but then I'm not sure how to work with the resulting long.

Any suggestions?
Mar 5 '08 #1
7 1839
On 2008-03-05, Je************* @gmail.com <Je************ *@gmail.comwrot e:
Is there a simple way to twiddle the bits of a float? In particular, I
would like to round my float to the n most significant bits.

For example - 0.123 in binary is 0.000111111
Rounding to 4 bits I get 0.0001.

I can pack and unpack a float into a long
e.g.
struct.unpack(' I',struct.pack( 'f',0.123))[0]
but then I'm not sure how to work with the resulting long.

Any suggestions?
Just use the bitwise and/or/not operators: & | ~

--
Grant Edwards grante Yow! Half a mind is a
at terrible thing to waste!
visi.com
Mar 5 '08 #2
On 2008-03-05, Grant Edwards <gr****@visi.co mwrote:
On 2008-03-05, Je************* @gmail.com <Je************ *@gmail.comwrot e:
>Any suggestions?

Just use the bitwise and/or/not operators: & | ~
Oh, I forgot to mention the shift operators << and >>

--
Grant Edwards grante Yow! All of life is a blur
at of Republicans and meat!
visi.com
Mar 5 '08 #3
On Mar 5, 10:48 pm, Grant Edwards <gra...@visi.co mwrote:
On 2008-03-05, Grant Edwards <gra...@visi.co mwrote:
On 2008-03-05, Jeff.Goldfin... @gmail.com <Jeff.Goldfin.. .@gmail.comwrot e:
Any suggestions?
Just use the bitwise and/or/not operators: & | ~

Oh, I forgot to mention the shift operators << and >>

--
Grant Edwards grante Yow! All of life is a blur
at of Republicans and meat!
visi.com
thanks for the reply but I'm still unsure as to how to continue. Using
the bitwise operators will help me deal with integers but I really
want to work with floats. For instance - which bits do I twiddle to
round my float to the nearest number of bits?

Jeff
Mar 5 '08 #4
On 2008-03-05, Je************* @gmail.com <Je************ *@gmail.comwrot e:
thanks for the reply but I'm still unsure as to how to
continue. Using the bitwise operators will help me deal with
integers but I really want to work with floats.
In your original post, you said that you've got the values as
integers.
For instance - which bits do I twiddle to round my float to
the nearest number of bits?
The format of a float (actually Python uses doubles) depends on
your platform, but in all likelihood it's the IEEE-754 64-bit
format.

googling for "IEEE-754 format" finds some good references:

http://en.wikipedia.org/wiki/IEEE_fl...point_standard
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
http://www.psc.edu/general/software/...ieee/ieee.html

--
Grant Edwards grante Yow! Well, I'm INVISIBLE
at AGAIN ... I might as well
visi.com pay a visit to the LADIES
ROOM ...
Mar 5 '08 #5
On Mar 5, 3:25*pm, "Jeff.Goldfin.. .@gmail.com"
<Jeff.Goldfin.. .@gmail.comwrot e:
I can pack and unpack a float into a long
e.g.
struct.unpack(' I',struct.pack( 'f',0.123))[0]
but then I'm not sure how to work with the resulting long.

Any suggestions?
One alternative to using struct is to use math.ldexp and math.frexp:
>>m, e = frexp(pi)
m
0.7853981633974 4828
>>e
2
>>int(m*2**53 )
707423775202844 0L

Then you can do your bit twiddling on int(m*2**53), before using
ldexp to 'repack' the float.

Mark
Mar 5 '08 #6
Mark Dickinson wrote:
Jeff Goldfin wrote:
>I can pack and unpack a float into a long
e.g.
struct.unpack( 'I',struct.pack ('f',0.123))[0]
but then I'm not sure how to work with the resulting long.

Any suggestions?

One alternative to using struct is to use math.ldexp and math.frexp:
>>>m, e = frexp(pi)
m
0.7853981633974 4828
>>>e
2
>>>int(m*2**5 3)
707423775202844 0L

Then you can do your bit twiddling on int(m*2**53), before using
ldexp to 'repack' the float.
Ah, those are handy. Jeff described his problem: "In particular,
I would like to round my float to the n most significant bits."
I think this works:

from math import frexp, ldexp, floor

def round_mantissa( x, nbits):
shifter = 1 << nbits
(m, e) = frexp(x)
m = floor(m * shifter + 0.5) / shifter
return ldexp(m, e)
--
--Bryan
Mar 6 '08 #7
On Mar 6, 11:00 am, Bryan Olson <fakeaddr...@no where.orgwrote:
Mark Dickinson wrote:
Jeff Goldfin wrote:
I can pack and unpack a float into a long
e.g.
struct.unpack(' I',struct.pack( 'f',0.123))[0]
but then I'm not sure how to work with the resulting long.
Any suggestions?
One alternative to using struct is to use math.ldexp and math.frexp:
>>m, e = frexp(pi)
m
0.7853981633974 4828
>>e
2
>>int(m*2**53 )
707423775202844 0L
Then you can do your bit twiddling on int(m*2**53), before using
ldexp to 'repack' the float.

Ah, those are handy. Jeff described his problem: "In particular,
I would like to round my float to the n most significant bits."
I think this works:

from math import frexp, ldexp, floor

def round_mantissa( x, nbits):
shifter = 1 << nbits
(m, e) = frexp(x)
m = floor(m * shifter + 0.5) / shifter
return ldexp(m, e)

--
--Bryan
Thanks for the help - your function seems to fit the bill even better
than gmpy since I don't need an external module. In my case I'll use
m = floor(m * shifter) / shifter instead of m = floor(m * shifter +
0.5) / shifter

Jeff

Mar 6 '08 #8

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

Similar topics

4
7852
by: Roger Leigh | last post by:
Hello, I'm writing a fixed-precision floating point class, based on the ideas in the example fixed_pt class in the "Practical C++ Programming" book by Steve Oualline (O' Reilly). This uses a long int to store the value, and the precision (number of decimal points) is variable (it's a templated class): template <size_t _decimal_places = 4> class FixedFloat {
4
3317
by: Dave | last post by:
Hi folks, I am trying to develop a routine that will handle sphere-sphere and sphere-triangle collisions and interactions. My aim is to develop a quake style collision engine where a player can interact with a rich 3D environment. Seem to be 90% of the way there! My problems are related to calculations where the result tends to zero (or another defined limit.) Have loads of cases where this kind of interaction occurs but this one
31
3687
by: JS | last post by:
We have the same floating point intensive C++ program that runs on Windows on Intel chip and on Sun Solaris on SPARC chips. The program reads the exactly the same input files on the two platforms. However, they generate slightly different results for floating point numbers. Are they really supposed to generate exactly the same results? I guess so because both platforms are supposed to be IEEE floating point standard (754?) compliant. ...
687
23765
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is basically the same. in C there arent the simplest things present like constants, each struct and enum...
10
2273
by: Shawn | last post by:
Hello all, I apologize as I am sure this has probably been dealth with before... but I am doing an exercise from "Practical C Programming" and I have been unable to get it to work perfectly due to problems with floating point arithmetic and I am looking for a way to solve it. See the code below... Given a certain amount of change (below $1.00) the program will tell you how many of each coin you will need to get that amount. The program...
7
3395
by: Vinoth | last post by:
I'm working in an ARM (ARM9) system which does not have Floating point co-processor or Floating point libraries. But it does support long long int (64 bits). Can you provide some link that would discuss about ways to emulate floating point calculations with just long int or long long int. For eg., if i've a formula X=(1-b)*Y + b*Z in floating point domain, i can calculate X with just long ints (but, some data may be lost in final division;...
15
3935
by: michael.mcgarry | last post by:
Hi, I have a question about floating point precision in C. What is the minimum distinguishable difference between 2 floating point numbers? Does this differ for various computers? Is this the EPSILON? I know in float.h a FLT_EPSILON is defined to be 10^-5. Does this mean that the computer cannot distinguish between 2 numbers that differ by less than this epsilon?
32
4121
by: ma740988 | last post by:
template <class T> inline bool isEqual( const T& a, const T& b, const T epsilon = std::numeric_limits<T>::epsilon() ) { const T diff = a - b; return ( diff <= epsilon ) && ( diff >= -epsilon ); } int main() { std::deque<double> pt ;
11
2073
by: Peter | last post by:
I have written this small app to explain an issue I'm having with a larger program. In the following code I'm taking 10 ints from the keyboard. In the call to average() these 10 ints are then added and Divided by the number of ints to return the average, a float. Can someone see why I get for example: if the total is 227 then divided by 10 I get a return of 22.00000 instead of the correct answer 22.7.
0
10443
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...
0
10216
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10002
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
9044
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
7543
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
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
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
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2921
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.