首页 > 解决方案 > 如何将 f(x) 作为用户输入并使其像使用 java 代码的公式一样工作?

问题描述

我是编码新手!如果你觉得这个问题很傻,那么我一开始就请你原谅!我试图用java解决二分法。而我成功地做到了!我将用户输入用于初始猜测 'a' 和 'b'!在我的代码中,我创建了一个存储“f(x) = x^3 - x - 1”的方法,当我调用此方法时,它会按照我给定的说明解决二分法。

我经历了很多答案,但他们无法满足我!我在下面添加我的程序,如果有人可以检查!

//二分法

package numericalMethods;

import java.util.*;

public class BisectionMethod {

    public static void main(String[] args) {


        double a, b, c;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter value of a : ");
        a = sc.nextDouble();
        System.out.print("Enter value of b : ");
        b = sc.nextDouble();
        System.out.print("Enter maximum iteration : ");
        c = sc.nextDouble();

        System.out.println();



        if ((f(a) < 0 && f(b) > 0) || (f(a) > 0 && f(b) < 0)) {

            for(int i = 1; i <= c; i++){

                System.out.println("*** For iteration " + i + " ***");
                System.out.println("a is a = " + a + " and b is b = " + b);
                System.out.println("So f(a) is f(a) = " + f(a) + " and " + "f(b) is f(b) = " + f(b));

                //declaration and calculation of root variable
                double x = (a+b)/2;

                System.out.println("For iteration " + i + " root is x = " + x);
                System.out.println("And f(x) is f(x) = " + f(x));
                System.out.println("Here f(a)*f(x) = " + (f(a) * f(x)) );

                //Condition for assignment of the value of root x!
                if(f(a)*f(x) < 0){
                    b = x;
                    System.out.println("As f(a)*f(x) < 0, we assign value of x to b.");
                    System.out.println("So now a and b are respectively, a = "+ a + " and b = " + b);
                    System.out.println();
                }else if (f(a)*f(x) >0) {
                    a = x;
                    System.out.println("As f(a)*f(x) > 0, we assign value of x to a.");
                    System.out.println("Now a and b are respectively, a = "+ a + " and b = " + b);
                    System.out.println();
                }
            }
        }else {
            System.out.println("The condition was not fullfilled!");
        }


    }

    //declares function
    public static double f(double x){
        return ((x*x*x)-x-4);

    }

}

标签: java

解决方案


您可以使用 ScriptEngineManager 使用 javascript 引擎评估数学表达式。

俄亥俄州 你需要先用它的替代品替换“x”:

String formula = "x/2 + x";
Integer X = 6;

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine eng = mgr.getEngineByName("JavaScript");

System.out.println(eng.eval(formula.replace("x", X)));

但是你的问题看起来像“家庭作业”,所以我怀疑这个解决方案是否可以接受。


推荐阅读