which is fastest way to inverse a number in c++?

Started by
16 comments, last by The Communist Duck 13 years, 2 months ago
not sure if there is a function for this



if its a positive , it makes it a negitive
if its a negitive then it makes it a positive



float num = 97.45;
num *=-1;
Advertisement
x = -x; ?

I would say its straight:
-num.

Is this worthy to worry about? I mean I've just done a test, and performance wise, difference are barely imposible to notice (testing on 1024^3 gave me ~1.10e-005 vs ~1.05e-005)

not sure if there is a function for this



if its a positive , it makes it a negitive
if its a negitive then it makes it a positive



float num = 97.45;
num *=-1;
That's called "negating", not "inversing", and yes x = -x is the answer.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
If you've got a lot of numbers you need to negate, you can batch negate them using whatever SIMD hardware you have at your disposal.

For example, with SSE:


size_t const count = 10000;
__declspec(align(16)) float values[count] = { ... }; // values to negate

__m128 zero = _mm_set_ps1(0.0f);
float* p = values;

// negate 16 values every iteration
for (size_t i = 0, n = count / 16; i < n; p += 16, ++i) {
__m128 a = _mm_load_ps(p);
__m128 b = _mm_load_ps(p+4);
__m128 c = _mm_load_ps(p+8);
__m128 d = _mm_load_ps(p+12);
a = _mm_sub_ps(zero, a);
b = _mm_sub_ps(zero, B);
c = _mm_sub_ps(zero, c);
d = _mm_sub_ps(zero, d);
_mm_store_ps(p, a);
_mm_store_ps(p+4, B);
_mm_store_ps(p+8, c);
_mm_store_ps(p+12, d);
}

// negate remaining values
for (float* p_end = values + count; p < p_end; ++p) {
*p = -(*p);
}


Of course, that's probably overkill.
You can check the sign bit and inverse it if necessary, but you have other things to worry about, than negating numbers don't you?
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Keep it simple. x = -x; Let the compiler perform any tricks required to make it fast. Worry about making your program run correctly before worrying about making it run fast. If you think this operation is too slow, profile it. Only then worry about it if it's truly a bottleneck (it shouldn't be).

...
That's called "negating", not "inversing", and yes x = -x is the answer.

A bit nitpicking: You're right: The usual name is negation. But on the other hand, negation is a specialization of the inverse with additive math in mind. See e.g. here on wikipedia. This is a similar distinction as with the neutral element, what is 0 for addition and 1 for multiplication.
Most FPUs have an instruction to change the sign of a floating point number. That would be the fastest way, but isn't very portable...
This article outlines several other methods.

This topic is closed to new replies.

Advertisement