指数函数在Java和Matlab中给出不同的结果

时间:2013-10-15 03:15:41

标签: java matlab

我有一个n乘2的数组'ppi'有整数值(有重复),第二个数组n乘1'gid'包含来自'ppi'的唯一整数值​​,第三个数组'X0'有0和1个值。下面是我想用Java实现的MATLAB代码 -

MATLAB版本 -

    gamma0 = 10; gamma1 = 10; beta = 20;
    delta = 0;weight=10;
    for i=1:length(gid)
    gconn = union(ppi(find(ppi(:,1)==gid(i)),2), ppi(find(ppi(:,2)==gid(i)),1));
    [a,b] = intersect(gid, gconn);
    u1 = (X0(i)*weight + sum(X0(b)==1))/(weight+length(gconn)); 
    u0 = ((1-X0(i))*weight + sum(X0(b)==0))/(weight+length(gconn));
    mrfpdf(i) = exp((1-X0(i))*(gamma0-beta*u1)+X0(i)*(gamma1-beta*u0))/(exp(gamma0-           beta*u1)+exp(gamma1-beta*u0));
    end

相同实现的Java代码

    double[] mrfpdf = new double[X0.length];
    Integer[] X = new Integer[X0.length];

    // find out unique class labels in ppi
    Set<Double> gid_set = new LinkedHashSet<Double>();
    for (int i = 0; i < ppi.length; i++) {
    for (int j = 0; j < ppi[0].length; j++) {
    gid_set.add(ppi[i][j]);
    }
    }
    System.out.println("unique gid_set: " + gid_set);
    Double[] gid = gid_set.toArray(new Double[gid_set.size()]);
    Arrays.sort(gid);

    int gamma0 = 10, gamma1 = 10, beta = 20, delta = 0;weight=10;
    for (int i = 0; i < gid.length; i++) {

    Set<Double> ppi1 = new HashSet<Double>();
    Set<Double> ppi2 = new HashSet<Double>();
    for (int k = 0; k < ppi.length; k++) {
    if (ppi[k][0] == gid[i])
    ppi1.add(ppi[k][1]);

    if (ppi[k][1] == gid[i])
    ppi2.add(ppi[k][0]);

    }

    Set<Double> gconn = new HashSet<Double>(ppi1);
    gconn.addAll(ppi2);
    Set<Double> a = new HashSet<Double>(gid_set);
    a.retainAll(gconn);
    java.util.List<Double> buff = new LinkedList<Double>(gid_set);
    int[] b = new int[a.size()];// get index of intersection elements in this array
    int x = 0;
    for (double j : a) {
    for (int c = 0; c < gid.length; c++) {
    if (j == gid[c]) {
    b[x] = c;
    x++;
    }
    }
    }
    java.util.List<Double> X0_list = new ArrayList<Double>();
    for (double z : X0) {
    X0_list.add(z);
    }
    int sum1 = 0;
    for (int y : b) {
    if (X0_list.get(y) == 1)
    sum1++;
    }
    int sum2 = 0;
    for (int y : b) {
    if (X0_list.get(y) == 0)
    sum2++;
    }
    u1 = (int) ((X0[i] * weight + sum1) / (weight + gconn.size()));
    u0 = (int) (((1 - X0[i]) * weight + sum2) / (weight + gconn.size()));
    mrfpdf[i] = (Math.exp((1 - X0[i]) * (gamma0 - beta * u1) + X0[i]* (gamma1 - beta * u0)) / (Math.exp(gamma0 - beta * u1) + Math.exp(gamma1 - beta * u0)));

    }// end for(int i : gid)
    }

有人可以告诉我为什么mrfpdf数组中的值在Java和Matlab代码中有所不同吗? Java代码仅产生0.99和0.5值,而Matlab没有任何0.5值

由于

1 个答案:

答案 0 :(得分:1)

你的matlab代码使用双精度,而java代码使用整数(例如u0和u1)