一元N次方程,转为字符串在oracle用power函数计算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33369215/article/details/53908755

这几天做任务的时候有个需求,从数据库读取出公式,现在要用这个计算公式

Y=0.004x^11 - 0.265*x^6 + 0.382x^2 + 10.46x - 4.772  计算出Y值,

下面介绍一种比较取巧的方法,适用于有oracle数据库的:

思路:  

1.Oracle有一个自带的函数power(n,m);  n的m次方,用power来替换 "^" 最后拼接成适用于oracle的字符串使用

2.转换为的字符串为:0.004*power(12.5,11)-0.265*power(12.5, 6)+0.382*power(12.5, 2)+10.46*12.5-4.772

3.带入oracle查询就可以得出我们要的值:


下面写成了一个适用于一元n次行数通用的方法:

package com.sinitek.demo1;

/**
 * Created with IntelliJ IDEA
 * Date:    2016/12/28
 * Time:    下午2:34
 */

public class Review_7_yicihanshu {
    public static void main(String[] args){
        double paramValue = 12.5;
        String formula = "0.004x^11 - 0.265*x^6 + 0.382x^2 + 10.46x - 4.772";
        Review_7_yicihanshu review_7_yicihangshu = new Review_7_yicihanshu();
        String str = review_7_yicihangshu.getFormula(formula);
        str = str.replaceAll("x",paramValue+"");
        System.out.println(str);
    }

    public String getFormula(String formula){
        String str = "";
        formula = formula.replaceAll("\\s","").replaceAll("\\*","");//去掉空格和计算公式中的*
        String flag = formula;
        flag = flag.replace("+","-");
        String[] str2 = flag.split("-");//按"-"号分割
        int count = -1;//记录当前运算符
        for(int i = 0 ; i < str2.length ; i++){
            count += str2[i].length()+1;//记录当前运算符在原来字符串中的位置
            str2[i] = str2[i].replaceAll("x","*x");
            String ysf = i==str2.length-1 ? "" : formula.substring(count, count+1); //运算符
            if (str2[i].indexOf("^")==-1) {
                str += i==str2.length-1 ? str2[i] : str2[i]+ysf;
            } else {
                str2[i] = str2[i].replaceAll("x\\^","power(x, ");
                str += i==str2.length-1 ? str2[i]+")" : str2[i]+")"+ysf;
            }
        }
        return str;
    }
}
运行结果:



运行结果的就是我们想要的字符串,最后带入数据库查询,就可以了


希望对大家有所帮助.

猜你喜欢

转载自blog.csdn.net/qq_33369215/article/details/53908755