java - 程序每次都给出相同的结果,而它应该是随机的

标签 java reduce pi

该程序的目标是采用 2 个随机变量作为分数,并查看它们是否已采用简化项。假定的概率为 6/(pi^2)。我运行了 1,000 种不同的变量组合,并确定有多少已经减少,有多少尚未减少。然后我求解 pi。

但是每次运行它时,输出都会给出“pi is 2.449489742783178”。

有人知道为什么吗?谢谢。

import java.util.*;

public class ratio1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int nonReducedCount = 0; //counts how many non reduced ratios there are
        for(int i =1; i<=1000; i++){

            Random rand = new Random();
            int n = rand.nextInt(1000)+1;  //random int creation
            int m = rand.nextInt(1000)+1;
            //Ratio ratio = new Ratio(n,m);
            if (gcd(n,m)> 1 ){ // if the ratio was not already fully reduced
                nonReducedCount++; // increase the count of non reduced ratios
            }   
        }

        int reducedCount = 1000 - nonReducedCount; //number of times the ratio was reduced already
        double reducedRatio = reducedCount / nonReducedCount; //the ratio for reduced and not reduced
        reducedRatio *= 6;
        reducedRatio = Math.sqrt(reducedRatio);
        System.out.println("pi is " + reducedRatio);
    }

    public static int gcd(int a, int b) { return b==0 ? a : gcd(b,a%b); }

}

最佳答案

当您将两个整数相除时,您会得到整数除法,并得到整数结果,即使您稍后将结果分配给double。尝试一下

double reducedRatio = (double)reducedCount / nonReducedCount;

即将操作数之一转换为double

关于java - 程序每次都给出相同的结果,而它应该是随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550202/

相关文章:

java - Math.(E|PI) 和 StrictMath 有什么区别?

Java ThreadPoolExecutor - 关闭特定线程?

java - 还有其他方法可以加载吗?

Java数据结构建议

javascript - 我如何获取一个对象数组并减少它,以便组合重复对象键的数据?

javascript - 如何使用 reduce 计算多个数组的交集?

Javascript 减少功能不工作

java - Pi 数计算得出 3.22

multithreading - 并行但速度较慢

java - 如何在 java 中等待一组线程 'really' 完成?