4
I have this expression stored in a String
:
1 * Math.pow(x, 3.0) + 4 * Math.pow(x, 2.0) + 1 * Math.pow(x, 1.0) + 27
However, I use a derivation library that only accepts the character ^
to make potentiation, then I make a conversion in this String
, being like this:
1*x^3.0+4*x^2.0+1*x^1.0+27
The derivation function returns me a String
derived in the same String
converted (1.0+3.0*x^2.0+8.0*x
), and I need to calculate the derived expression with the function eval()
, who only accepts the Math.pow()
as a potentiation function. I tried to use:
str = str.replaceAll("[x\\^]", "Math.pow\\(\\x\\,");
str = str.replaceAll("[(?:\\,(?=0-9))]", "1");
And the first line already helps a lot, but I don’t know very well how I would add the exponent with parenthesis after the comma or how to know the exponent.
EDIT: I created the following code:
static String reConvertString(String str) {
Pattern patterne = Pattern.compile("[^\\^]*\\^");
Matcher matchere = patterne.matcher(str);
int count = 0;
while (matchere.find()) {
count++;//conta a quantidade de ocorrencias do caractere ^
}
for(int i=0;i<count;i++) {
int index = str.indexOf("^");
str = str.replaceFirst("\\^", "z");//substituo por um caractere qualquer depois que acho a primeira ocorrencia
System.out.println(index);
str = str.replaceFirst("[xz]", "Math.pow\\(\\x\\, ");//o x^2.0 agora fica xz com o replace
String teste=str.substring(index+1, index+2);//pega a potência
str = str.replace(" ", teste+")");//fecha o parêntese da função
}
return str;
}
But my output was like this:
10.0*Math.Pow(Math.Pow(x,4),t)Z4.0-15.0*xz2.0
I don’t know where the t
.