Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between a number (of type double) with decimal places and one without - c++

I am trying to implement a simple decimation algorithm in c++. I have two arrays, say p & q, where the subscripts are related to each other by the following relation:

p[k] = q[0.5*k]. This means that the following sequence should hold valid:

p[0] = q[0]  
p[1] = 0  
p[2] = q[1]  
p[3] = 0  
p[4] = q[2]  

and so on...

Please note that p[k] takes on a value only and only when the result of (0.5*k) contains no decimal places (or has 0 in decimal) and does not use any rounding off etc.

My question is: Is there a way to distinguish between an integer (a number with no decimal places or only 0 in decimal, say 2.0) and a number with decimal places in C++, provided both are cast to double?

eg.) 2.0 is an integer cast to double. 2.1 is a number with decimal places.
eg. 2) * 0.9*2 should put 0 into array p while 0.9*10 should put q[9] into array p.*

If I use the statement, (int) (0.5*k), then I end up with an integer in every case, irrespective of the value of k.

Edit: The 0.5 in the above case is only illustrative. It could be any number, say 2, 2.5, 0.9, 0.95 etc.)

Any help is most welcome,
Thanks,
Sriram.

like image 462
Sriram Avatar asked Nov 17 '25 05:11

Sriram


2 Answers

Assuming k is of an integer type, you could use if (k % 2 == 0) ... to check if kis divisible by two:

if (k % 2 == 0)
  p[k] = q[k / 2];
else
  p[k] = 0;

This can also be expressed using the ternary operator:

p[k] = (k % 2 == 0) ? q[k / 2] : 0;
like image 115
NPE Avatar answered Nov 18 '25 20:11

NPE


Presuming that the coef can be anything else,

p[floor(coef*k)] = (fabs(coef*k-floor(coef*k))<1E-6)?q[k]:0;
like image 33
Shelwien Avatar answered Nov 18 '25 19:11

Shelwien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!