Jump to content
  • Advertisement
Sign in to follow this  

What is the faster way to check whether 2 floats have the same sign?

This topic is 4303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
check the sign bits?

I am no bit twiddler, but here is some code to play around with:


#include <iostream>
#include <string.h>

int main (int argc, char * const argv[]) {
float f = -118.625;
unsigned long src;

memcpy(&src, &f, sizeof(float));

int s;
s = (src & 0x80000000UL) >> 31;

std::cout << s << std::endl;

return 0;
}




[Edited by - visage on August 9, 2006 5:57:17 PM]

Share this post


Link to post
Share on other sites
EDIT: WAY OFF!

No clue, read visage's post.

My thoughts:

First, float variables are 32 bit, 1 bit for the sign, 8 for the exponent, and 23 for fraction. This should work, since the sign byte is the highest bit in the float variable. Reference.

Share this post


Link to post
Share on other sites
I would say also, that the mult would be the easiest to read, easiest to maintain, and almost the fastest. Problem with the mult is that of course, you may lose precision....

-.00000000001 * 0.00000000001 ~ 0 = 0
-.00000000001 * -.000000000001 ~ 0 = 0

Share this post


Link to post
Share on other sites
Quite possibly true on the mult...

What about:

bool sameSign = ((x>0) + (y>0) - (x<0) - (y<0) != 0);

It treats 0 as being the same sign as -1 and 1... which I suppose you'd want...

Share this post


Link to post
Share on other sites
I would interpret both floats as unsigned ints, xor them together and test for the sign bit (this might be different on different platforms, since it depends on endianness).

It looks like this:
bool have_same_sign(float x, float y){
unsigned a=*reinterpret_cast<unsigned *>(&x);
unsigned b=*reinterpret_cast<unsigned *>(&y);
return !((a^b)&0x80000000u);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!