3

hello everyone i have this code that makes functions in mathematics but with this function the result is wrong o.O

x=0

"-3*X^2-16*X+2"

Code:

public static void main(String[] args) throws Exception {

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("X", 0);

        Object operation = engine.eval("-3*X^2-16*X+2");
        //Object operation2 = engine.eval("(X+3)");

        System.out.println("Evaluado operacion 1: " + operation);
        //System.out.println("Evaluado operacion 2: " + operation2);

    }

the result is 2 but i get 4

Evaluado operacion 1: 4

i have other code that i made

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gustavo_santa;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JOptionPane;

/**
 *
 * @author osmarvirux
 */
public class SerieB {
    //xi and x4
    int xi;
    int x4;
    //f(x) function variables
    String positive_negative;
    int num_one;
    int elevation_one;
    String add_subtract_one;
    int num_two;
    int elevation_two;
    String add_subtract_two;
    int num_three;
    //results
    String xi_result;
    String x4_result;

    public SerieB(int xi, int x4, String positive_negative, int num_one, int elevation_one, String add_subtract_one, int num_two, int elevation_two, String add_subtract_two, int num_three) {
        this.xi = xi;
        this.x4 = x4;
        this.positive_negative = positive_negative;
        this.num_one = num_one;
        this.elevation_one = elevation_one;
        this.add_subtract_one = add_subtract_one;
        this.num_two = num_two;
        this.elevation_two = elevation_two;
        this.add_subtract_two = add_subtract_two;
        this.num_three = num_three;
    }

    public void Procedure_xi(){
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        if (positive_negative == "-"){

           try {
            xi_result=(num_one*(Math.pow(xi, elevation_one)))+add_subtract_one+(num_two*(Math.pow(xi, elevation_two)))
                    +add_subtract_two+num_three;
            Object result = engine.eval(xi_result);
            System.out.println(xi_result+" = "+result);
            } catch(ScriptException se) {
                se.printStackTrace();
            }           
        }else{
             try {
            xi_result=((-num_one*(Math.pow(xi, elevation_one)))+add_subtract_one+(num_two*(Math.pow(xi, elevation_two)))
            +add_subtract_two+num_three);
            Object result = engine.eval(xi_result);
            System.out.println(xi_result+" = "+result);
            } catch(ScriptException se) {
                se.printStackTrace();
            }       

        }
    }
    public void Procedure_x4(){
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        if (positive_negative == "-"){

           try {
            x4_result=(num_one*(Math.pow(x4, elevation_one)))+add_subtract_one+(num_two*(Math.pow(x4, elevation_two)))
                    +add_subtract_two+num_three;
            Object result = engine.eval(x4_result);
            System.out.println(x4_result+" = "+result);
            } catch(ScriptException se) {
                se.printStackTrace();
            }           
        }else{
             try {
            x4_result=((-num_one*(Math.pow(x4, elevation_one)))+add_subtract_one+(num_two*(Math.pow(x4, elevation_two)))
            +add_subtract_two+num_three);
            Object result = engine.eval(x4_result);
            System.out.println(x4_result+" = "+result);
            } catch(ScriptException se) {
                se.printStackTrace();
            }       

        }
    }
    public static void main(String[] args){
        //-3x^2-16x+2
        SerieB obj = new SerieB(0, 1, "+", -3, 2, "-", 16, 1, "+", 2);
        obj.Procedure_xi();
        obj.Procedure_x4();
    }


}

the result with this code is 2 but i wanna use

ScriptEngineManager manager = new ScriptEngineManager();ScriptEngineManager manager = new ScriptEngineManager();

because is a library and i think is more precise and i dont wanna use my code because there are many lines and i dont know if is 100% efficient. someone can help me? or give me a recomendation to resolve this mathematic functions? thanks a lot

Alien Java
  • 75
  • 2
  • 12

3 Answers3

1

The result you're getting is correct.

The confusion arises from the fact that what you're assuming to be the power operator (^) is actually the bitwise XOR operator in JavaScript (you're using a JavaScript script engine).

So, evaluating 0 ^ 2 yields 2, while evaluating Math.pow(0, 2) yields 0, hence the difference.

To get the result you expect, the expression would have to read:

-3*Math.pow(X,2)-16*X+2

You could pre-process the expression to replace the exponential operations with invocations of Math.pow():

let X = 0;
let expression = "-3*X^2-16*X+2"
let processed = expression.replace(/(\w+)\^(\w+)/g, 'Math.pow($1,$2)');

console.log(processed); // prints "-3*Math.pow(X,2)-16*X+2"
console.log(eval(processed)); // prints "2"

Using the script engine, that could look like:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("X", 0);
engine.put("expression", "-3*X^2-16*X+2");
engine.put("processed", engine.eval("expression.replace(/(\\w+)\\^(\\w+)/g, 'Math.pow($1,$2)')"));

System.out.println(engine.eval("eval(processed)")); // 2.0

Or, if you prefer to do the regular expression replacement in Java:

String expression = "-3*X^2-16*X+2";
String processed = expression.replaceAll("(\\w+)\\^(\\w+)", "Math.pow($1,$2)");

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("X", 0);

System.out.println(engine.eval(processed)); // 2.0
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

I think what's happening is your program is evaluating

(-3*0)^2 - 16*0 + 2 = 0^2 +2 = 2+2 =4

because the operator ^ in computer science mean bitwise exclusive or, which basically means if the bits are both 1 or 0 then change them to 0, else 1. And 2 is represented by 10 while 0 is 0 so 2^0 = 2

Try replacing ^2 with *X alternatively you can use Math.pow(X,n) , if you need exponentiation to some power n, but for squaring it's better to just write it out as X*X

The Below is Outdated Due to Edits to Question, but is still functional:

In the second part of your question you wrote

Object operation = engine.eval("-3*(X^2)-16*X +2");
String processed = operation.replace(/(\w+)\^(\w+)/g, 'Math.pow($1,$2)');

based on an answer by another user. You should have written

String expr = "-3*(X^2)-16*X +2";
String processed = expr.replaceAll("(\\w+)(\\^)(\\w+)", 'Math.pow($1,$2'));
Object operation = engine.eval(processed);
Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27
0

You have incorrect syntax for power. Replace -3*X^2-16*X+2 with -3*Math.pow(X,2)-16*X+2. See Javascript, What does the ^ (caret) operator do?

Community
  • 1
  • 1
Ville Oikarinen
  • 400
  • 1
  • 11