Aboozar Roosta
Aboozar Roosta

Reputation: 71

rounding to desired digits in MATLAB and C

I've read the questions regarding the implementation of rounding in C, inspired by MATLAB round function and I followed their advice but the result is not at all what it should be. Here's part of my code regarding this issue:

    movmean_h[i]=(double)sum/(f-b);
    mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);
    movmean_h[i]=(double)round(movmean_h[i]*n)/n;
    mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);

And part of the result is like this(this code is run in a loop):

 movmean_h[10261]=2.283693e-13   movmean_h[10261]=1.668138e-06
 movmean_h[10261]=2.283693e-13   movmean_h[10261]=1.668138e-06
 movmean_h[10262]=2.288172e-13   movmean_h[10262]=1.483963e-06
 movmean_h[10263]=2.292687e-13   movmean_h[10263]=-8.838173e-07
 movmean_h[10264]=2.297219e-13   movmean_h[10264]=0.000000e+00
 movmean_h[10265]=2.292835e-13   movmean_h[10265]=2.138378e-06
 movmean_h[10266]=2.288319e-13   movmean_h[10266]=1.409754e-06
 movmean_h[10267]=2.283839e-13   movmean_h[10267]=0.000000e+00
 movmean_h[10268]=2.279412e-13   movmean_h[10268]=-2.147484e-06
 movmean_h[10269]=2.275056e-13   movmean_h[10269]=-2.147484e-06
 movmean_h[10270]=2.270787e-13   movmean_h[10270]=-2.147484e-06
 movmean_h[10262]=2.288172e-13   movmean_h[10262]=1.483963e-06
 movmean_h[10263]=2.292687e-13   movmean_h[10263]=-8.838173e-07
 movmean_h[10264]=2.297219e-13   movmean_h[10264]=0.000000e+00
 movmean_h[10265]=2.292835e-13   movmean_h[10265]=2.138378e-06
 movmean_h[10266]=2.288319e-13   movmean_h[10266]=1.409754e-06
 movmean_h[10267]=2.283839e-13   movmean_h[10267]=0.000000e+00
 movmean_h[10268]=2.279412e-13   movmean_h[10268]=-2.147484e-06
 movmean_h[10269]=2.275056e-13   movmean_h[10269]=-2.147484e-06
 movmean_h[10270]=2.270787e-13   movmean_h[10270]=-2.147484e-06

The answers do not match at all, not in order and not in the decimals, which in theory they would match.

And 'n' is defined as:

long int n=pow(10,15);

So my question is why my code is wrong, or is there something I'm missing? By the way I am writing my C code for a MATLAB mex-file.

Upvotes: 1

Views: 92

Answers (2)

chux
chux

Reputation: 153468

Code lacked a declaration of declaration of double round(). Older compilers allow this, yet interpret the result then an int. Code output is then quite bizarre. The hint, for me, was that many nearby double inputs had the same result.

// add
#include <math.h>

Upvotes: 2

dasdingonesin
dasdingonesin

Reputation: 1358

10^15 doesn't fit into a long int on a Windows machine. Use a double.

double n = pow(10, 15);
movmean_h[i]=(double)sum/(f-b);
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);
movmean_h[i]=round(movmean_h[i]*n)/n;
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);

Upvotes: 0

Related Questions