秦九韶算法实现

/**
     * 设定多项式的系数,为1.0 ~ 10.0之间的随机数
     * @param num
     * @return
     */
    public ArrayList getRandomCoefficient(Integer num){
        ArrayList arrayList = new ArrayList();
        Random random = new Random();
        while (num >=0){
            arrayList.add((double) Math.round(random.nextDouble()*10));
            num--;
        }
        return arrayList;
    }

    /**
     * 秦九韶算法计算结果
     * @param arrayList
     * @param X
     * @return
     */
    public Double getResultByQjsh(ArrayList arrayList,Float X){

        ArrayList doubleLists = (ArrayList) arrayList.clone();
        Double V = doubleLists.get(0); // b0 = a0
        doubleLists.remove(0);
        long start = System.currentTimeMillis();
        for (Double An:
             doubleLists) {
            V = X * V + An;   //B(i) = B(i-1)*x + Ai
        }
        long end = System.currentTimeMillis();
        logger.info("秦九韶算法所用时间为:"+(end - start) + "毫秒");
        return V; //f(Xn) = V
    }

    /**
     * 传统的多项式计算方式
     * @param arrayList
     * @param X
     * @return
     */
    public Double getResultByOld(ArrayList arrayList,Float X){
        /*
        * 1.多项式系数
        * 2.各个X项的幂 ,ArrayList xlists
        * 3.两层循环求多项式的值
        * */
       /* int lenc = arrayList.size();
        int lenx = xlists.size();
        float temp = 0;
        double P = 0;
        for (int i = 0; i < lenc; i++) {
            double coefficient = arrayList.get(i);
            for (int j = 0; j < lenx; j++) {
                Integer integer = xlists.get(j);
                while (integer >= 0){
                    temp = temp*X;
                }
            }
            P = P + coefficient*temp;
        }*/
//        return P;
        int N = arrayList.size() - 1;//系数个数的大小减去1就是X项的最高次
        Double res = 0D;
        long start = System.currentTimeMillis();
        for (Double An:
             arrayList) {
            Double Xn = 1D;
            int i = 0;
            while(i  randomCoefficient = getRandomCoefficient(10);
        Double resultByQjsh = getResultByQjsh(randomCoefficient, 8f);
        logger.info("计算结果为:"+resultByQjsh);
        Double resultByOld = getResultByOld(randomCoefficient, 8f);
        logger.info("计算结果为:"+resultByOld);
    }

 

你可能感兴趣的:(算法)