## better way to do this?

5 posts / 0 new
Author
Message

This is a simple issue, but the fix I used seems like a hack to me.

float foo=0.0;

(assign a value to foo)

if abs(10*foo >100)

cntxcs = cntxcs+1;

Here's the deal. I want to know if abs( foo) is >1 0, but I finally looked close ennough to see that abs deals with ints -- explained my strange issue of short counts,

Multiplying by 10 gives me the int that I need, but I really don't like it.

Somebody please show me the simple and clear way to do this.

Thanks,

hj

ford2go wrote:

if abs(10*foo >100)

cntxcs = cntxcs+1;

ford2go wrote:

Here's the deal. I want to know if abs( foo) is >1 0,

`1 0` is supposed to be `10`, right?

Then just do

```if (foo < -10 || foo > 10)
...```

no need to involve `abs`.

Or you can simply do

```if ((foo >= 0 ? foo : -foo) > 10)
...```

just to see which version produces a better code.

ford2go wrote:
but I finally looked close ennough to see that abs deals with ints -- explained my strange issue of short counts,

This is not entirely accurate. It actually depends on the language. What language are you talking about: C or C++?

In C `abs` indeed deals with `int`. But C also has `fabs` and `fabsf` that work with `double` and `float` respectively. You can do

```if (fabsf(foo) > 10)
...```

but it might end up being less efficient than the previous variants.

In C++ `abs` is overloaded and can deal with all arithmetic types by itself.

ford2go wrote:
Multiplying by 10 gives me the int that I need, but I really don't like it.

Then don't.

Then again there is also an issue of your `foo` being a `float`. Why `float`? Does it have to be `float`? Floating-point types are quite "heavy", you know. Maybe you can use fixed-point format from the very beginning, i.e. use an integer variable that is already "multiplied by 10" internally? But there's no way to say say without knowing the context.

Dessine-moi un mouton

Last Edited: Fri. May 31, 2019 - 06:04 AM

I agree with Andrey but just to point out that the math lib has fabs() should you ever need it.

Thanks for the plethora of comments. I apologize for the poor post.  A coworker once referred to me as a dyslexic typist -- and it's pretty true.

foo ( not its real name :) ) pretty much has to be a float

Thanks again,

hj