Normal Distribution Calculation having repeated answers and incorrect

Viewed 113

I'm writing a program that calculates the value of the normal distribution function given to me here:

Normal Distribution Equation

The program is supposed to ask the user for the mean μ and the Standard Deviation σ for the normal distribution showed above. The program then asks for N values of x and then asks for each value of x, one by one. After each value x it writes out the corresponding value of the function.

This is my code so far:

#define _USE_MATH_DEFINES
#include <stdio.h>
#include <math.h>

int main() {

int j;
double u, stddev, N, result, x;

printf("Enter u and stddev for the Normal Distribution:\n");
  scanf("%lf %lf",&u, &stddev);
printf("Enter how many values of x (N) for the Normal Distribution:\n");
  scanf("%lf",&N);

for (j=0; j<N; j++) {

printf("Enter a value for x: \n");
  scanf("%lf",&x);
result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(1/2)*((x-u)/stddev)*((x-u)/stddev));
printf("%.6lf\n", result);

 }
}

I'm basically done but the answers the program is giving me are wrong when compared to my answers from my calculator. For instance, when I make N = 3 no matter what I put for the 3 values of x, the answer it gives me for each are the same when they shouldn't be.

So I know my issue lies in this line of code:

result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(1/2)*((x-u)/stddev)*((x-u)/stddev));

Am I just writing the function wrong in the program? I must be, for it not to work.

1 Answers

Your code is clean and functional. Good work so far.

You were correct about which line needed changing - The issue is that using integer division results in an integer, so 1 / 2 results in a value of 0. This can be remedied by using a single double value: 0.5, or by dividing using doubles 1.0 / 2.0.

result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(0.5)*((x-u)/stddev)*((x-u)/stddev));

I tested out your code after making these changes try it online, and they match up perfectly with the formula on wolfram alpha, as well as what you said in the comments.

For example:

μ=2, σ=3, x=7 results in 0.033159
μ=3, σ=7, x=0 results in 0.051991
μ=4, σ=4, x=4 results in 0.099736
Related