Search code examples
javamachine-learninggaussian

Gaussian distribution function different answer for program and math


I write down a code to implement Gaussian distribution function.

The code block

import java.lang.Math.*;
public class gauss {
public static void main(String args[]){

    gauss c = new gauss();
    c.gu1(5.0,3.0,2.0);



}
public static double gu1(double mu,double sigm2,double x)
{
    double a;
    
    a=1/(Math.sqrt(2*Math.PI))*sigm2;
    double b;
    
    b= Math.exp(-0.5)*(Math.pow(((x-mu)/sigm2)),2);
    double z= a*b;
    System.out.println(z);
    return(z);
    }
}

Input: x = 2, μ = 5 and σ = 3 Output: 0.7259121735574301

However, if I solve it mathematically using pen and paper I got 0.0805 as answer.

I did not find out why there is such a difference with programming answer and manual answer?

Gaussian distribution formula

enter image description here


Solution

  • The expressions for a and b are wrong. Should be

    a=1/(Math.sqrt(2*Math.PI))/sigm2;
    b= Math.exp(-0.5*Math.pow((x-mu)/sigm2,2));