Reputation: 468
Is this the correct way to write the normal distribution function http://en.wikipedia.org/wiki/Normal_distribution or should I be using the pow function? I am really confused so help would be greatly appreciated :)
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>
int main()
{
double u,s, N, x1,math1, math2, math3,n, v, x;
printf("Enter Mean: ");
scanf("%lf", &u);
printf("Enter Standard Deviation: ");
scanf("%lf", &s);
printf("Enter Number Of Inputs: ");
scanf("%lf", &N);
for (v=1; v<=N; v++)
{
printf("Enter Value: ");
scanf("%lf", &x);
n=(-1/2);
printf("f(x)= ");
math1 =1/(s*sqrt(2*M_PI));
math2= (x-u)/s * (x-u)/s;
math3= M_E * exp(n);
x1 = math1 * exp(math3)*exp(math2);
printf("%lf \n", x1);
}
system("Pause");
}
Upvotes: 0
Views: 3438
Reputation: 213298
It's too hard to read your code, but I can tell it's wrong. Here is a short version:
double twopi = 8.0 * atan(1.0); // preferable to using M_PI
double x = ..., sigma = ..., mu = ...;
double y = (1.0 / (sigma * sqrt(twopi))) *
exp(-(x - mu)*(x - mu) / (2.0 * sigma * sigma));
Notice how I translate the mathematical formula directly to an expression in C... this makes it easy to verify that the code is correct. It's a bit harder when you use a bunch of temporary variables math1
, math2
, math3
...
Remember: exp()
is the same thing as its counterpart in mathematics, exp
. So exp(x)
is ex. Once you realize this, you will see the errors in your code.
Upvotes: 4