user2828488
user2828488

Reputation: 65

Wrong answer in Normal Distribution in C

I have applied the normal distribution function using the equation given in this link: http://en.wikipedia.org/wiki/Normal_distribution

I made this code for normal distribution

float m=2.0;
float s=0.5;
float x[3]={1.0, 2.0, 3.0};
float xs[3];
const float pi = 3.141;

for (int i=0; i<3; i++)
{
    xs[i]=(1/s*sqrt(2*pi))*exp(-(pow(x[i]-m,2)/2*pow(s,2)));
    printf("\n%f",xs[i]);
}

The answer for this code is 4.42, 5.01, 4.42

and I have the same code in Matlab

x_s_new=[1 2 3];
x_s=2+0.5.*randn(1,9);
x_s=x_s_new+0.5.*randn(1,3);
plot(x_s_new)

but the answers in matlab is 0.8 , 1.9 , 3.7

Can anyone tell me where I am going wrong?

I want to apply normal distribution using C

Thanks :)

Upvotes: 0

Views: 121

Answers (1)

A. Donda
A. Donda

Reputation: 8476

Your Matlab code is not the analogue of your C code. The C code computes the value of the probability density function of the normal distribution at certain points. The Matlab code generates random numbers from the normal distribution.

The Matlab code corresponding to the C code is

m = 2;
s = 0.5;
x = [1 2 3];

for i = 1 : 3
    xs(i) = (1/s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/2*s^2));
    fprintf('%f\n',xs(i));
end

and gives the same result

4.424183
5.013257
4.424183

However, there's a mistake because / in Matlab and C only applies to the immediate next operand. Correctly it would be

xs(i) = 1/(s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/(2*s^2)));

and correspondingly in C.

To translate the code using randn to C – to my knowledge there is no standard function in C to generate normally distributed random numbers, you need to find a library that includes such a function, or build it yourself starting from random().

Upvotes: 1

Related Questions