package com.ilivoo.common.utility.gaussian;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;

import com.ilivoo.common.utility.JsonUtils;

public class GaussianDistributionUtils {
    public static double calc(double u) {
	double y = Math.abs(u);
	double y2 = y * y;
	double z = Math.exp(-0.5 * y2) * 0.398942280401432678;
	double p = 0;
	int k = 28;
	double s = -1;
	double fj = k;

	if (y > 3) {
	    // 当y>3时
	    for (int i = 1; i <= k; i++) {
		p = fj / (y + p);
		fj = fj - 1.0;
	    }
	    p = z / (y + p);
	} else {
	    // 当y<3时
	    for (int i = 1; i <= k; i++) {
		p = fj * y2 / (2.0 * fj + 1.0 + s * p);
		s = -s;
		fj = fj - 1.0;
	    }
	    p = 0.5 - z * y / (1 - p);
	}
	if (u > 0)
	    p = 1.0 - p;
	return p;
    }

    public static Map<Integer, Float> getGaussianMap() throws Exception{
	return JsonUtils.json2HashMap(Object.class.getResourceAsStream("/com/ilivoo/common/utility/gaussian/Random.json"), Integer.class, Float.class);
    }

    public static void main(String[] args) throws Exception {
	Map<Integer, Float> map = new TreeMap<Integer, Float>();
	for (int i = 1000; i > 0; i--) {
	    for (double d = 0; d < 4.0; d += 0.0001) {
		double cal = calc(d);
		double result = cal * 1000;
		double ddd = result - i;
		if (ddd < 1 && ddd > 0) {
		    map.put(1000 - i, new Double(d).floatValue());
		    break;
		}
	    }
	}
	map.put(500, 0.0000f);
	try {
	    FileOutputStream out = new FileOutputStream(new File("Random.json"));
	    byte[] bytes = JsonUtils.object2Json(map).getBytes(Charset.forName("utf-8"));
	    out.write(bytes);
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}
