Draw Gaussian curve in Java

2019-01-26 18:32发布

I'm coding an interactive applet with Piccolo and I need to include a Gaussian curve (aka Normal distribution chart) inside it.

I imagine any kind of Java implementation would be enough, but I can't find any. Ideally, I'd like to pass a set of values and have the chart drawn in a panel, an image object or anything that can be embedded in an applet.

Before getting my hands dirty coding it myself, does anybody know of a working piece of code to do it?

Implementations in other languages are welcomed, as long as they are easily portable to Java.

2条回答
成全新的幸福
2楼-- · 2019-01-26 18:47

Don't know if it works, but Google threw up this code to plot a Gaussian distribution.

The home page for this project is here.

If Piccolo doesn't perform the plotting for you, I would perhaps use JFreeChart for the actual plotting, since it's widely supported and very capable. (I'm not familiar with Piccolo)

查看更多
仙女界的扛把子
3楼-- · 2019-01-26 19:02

Edit: It looks like the Apache Commons Math library has a statistics section. Specifically, a whole package on common Distributions. Hopefully theres some math people out there because I can't remember basic statistics... here's my attempt at using the their library. I just have a sliding window here and calculate the P between those values. Whats the real way to get a PDF from this? They only have a CDF function.

public void testNormalDist() throws MathException {
    DistributionFactory f = DistributionFactory.newInstance();
    NormalDistribution n = f.createNormalDistribution(0.0d, 1.0d);
    double lastx = Double.NEGATIVE_INFINITY;
    double nextx = Double.NEGATIVE_INFINITY;
    for (int i=-100; i < 100; i++) {
        nextx = i / 100d;
        System.out.println(n.cumulativeProbability(lastx, nextx));
        lastx = nextx;
    }
}

I assume you want the probability density function for the graph. The equations are on wikipedia, since I don't know how to include math markup here. Just use p(x) as your Y value and X as your X value and you can get a pretty easy 2-d graph from that.

Have you looked at Mathtools under Java?

Ok, how about this... you give it an array of X points (normalized, of course, you can convert your X pixels to these by dividing each pixel position by the width of your image), and it will return the heights of the distribution curve (again, multiply by your normalization factor). This is for the basic case where mean is 0 and standard deviation is 1.

public double[] normalDistBasic(double[] xarray, double mu) {
    double[] yarray = new double[xarray.length];
    double rad2pi = 2.50662827d;
    for (int off = 0; off < yarray.length; off++) {
        double x = xarray[off];
        double ss = -1d * x * x / 2d;
        yarray[off] = (-1f / rad2pi) * Math.exp(ss);
    }
    return yarray;
}

It should be pretty easy to implement one that takes arbitrary mean and standard deviation if one can't be found on the net.

查看更多
登录 后发表回答