package dc.jy;
import java.math.BigDecimal;
import java.math.MathContext;
public class Calculator {
public static void main(String[] args) {
String str = null;
str = "((45.34 + tan(sin(20 * 19^0.72 / 12))^3) - 2 * sin(2 + 362 - 3 / 4 + 7 * (80 + 3))/3)";
System.out.println("\n---> " + str);
System.out.println(
(45.34 +
Math.pow(Math.tan(Math.sin(20 * Math.pow(19.0, 0.72) / 12)), 3)
- 2 * Math.sin((2 + 362 - 3.0 / 4 + 7 * (80 + 3))) / 3)
);
System.out.println(cal(str));
}
final static String DIG = "0123456789.m";
final static String FUN = "sctlL";
final static int SCALE = 20;
final static int ROUNDINGMODE = BigDecimal.ROUND_HALF_UP;
final static MathContext MC = new MathContext(15);
/**
* 入口方法
*/
public static String cal(String str) {
str = str.replaceAll("[\\s ]", "");
str = str.replace("(-" , "(m");
str = str.replace("sin" , "s");
str = str.replace("cos" , "c");
str = str.replace("tan" , "t");
str = str.replace("ln" , "l");
str = str.replace("log" , "L");
StringBuilder buf = new StringBuilder(str);
check(buf);
int index = 0;
while (!isOK(buf)) {
char nextND = nextNotDig(buf, index);
int nextNDIndex = nextNotDigIndex(buf, index);
if (isDig(buf, index)) {
if(nextND == ')') {
buf.delete(nextNDIndex, nextNDIndex + 1);
buf.delete(index - 1, index);
index = 0;
continue;
}
char nextNextND = nextNotDig(buf, nextNDIndex);
int nextNextNDIndex = nextNotDigIndex(buf, nextNDIndex);
if((nextNextND == '\0' || nextNextND == ')' || notLower(nextND, nextNextND))) {
buf.replace(index, nextNextNDIndex,
baseCal(buf.substring(index, nextNextNDIndex), nextND));
index = 0;
} else {
index = nextNDIndex + 1;
}
} else if(isFun(buf, index)) {
char fun = buf.charAt(index);
if('(' != nextND) {
buf.replace(index, nextNDIndex,
baseCal(buf.substring(index + 1, nextNDIndex), fun));
index = 0;
} else {
index = nextNDIndex + 1;
}
} else {
index++;
}
}
return new BigDecimal(buf.toString().replaceAll("[\\(\\)]", "").replace("m", "-"))
.setScale(SCALE, ROUNDINGMODE).stripTrailingZeros().toPlainString();
}
static boolean isDig(StringBuilder buf, int index) {
return DIG.indexOf(buf.charAt(index)) > -1;
}
static boolean isFun(StringBuilder buf, int index) {
return isFun(buf.charAt(index));
}
static boolean isFun(char c) {
return FUN.indexOf(c) > -1;
}
static boolean isOK(StringBuilder buf) {
int len = buf.length();
for (int i = 0; i
if ("+-*/^sctlL".indexOf(buf.charAt(i)) > -1) return false;
}
return true;
}
static char nextNotDig(StringBuilder buf, int start) {
int len = buf.length();
for (int i = start + 1; i
if (DIG.indexOf(buf.charAt(i)) == -1) return buf.charAt(i);
}
return '\0';
}
static int nextNotDigIndex(StringBuilder buf, int start) {
int len = buf.length();
for (int i = start + 1; i
if (DIG.indexOf(buf.charAt(i)) == -1) return i;
}
return len;
}
static boolean notLower(char left, char right) {
return getLevel(left) >= getLevel(right);
}
static int getLevel(char op) {
if("+-".indexOf(op) > -1) return 0;
if("*/".indexOf(op) > -1) return 10;
if("^".indexOf(op) > -1) return 20;
if(FUN.indexOf(op) > -1) return 30;
if("(".indexOf(op) > -1) return 100;
throw new RuntimeException(op + " operator is invalid.");
}
static String baseCal(String str, char op) {
BigDecimal dig0 = null;
BigDecimal dig1 = null;
BigDecimal result = null;
if(isFun(op)) {
dig0 = new BigDecimal(str.replace("m", "-"));
} else {
int pos = str.indexOf(op);
dig0 = new BigDecimal(str.substring(0, pos).replace("m", "-"));
dig1 = new BigDecimal(str.substring(pos + 1, str.length()).replace("m", "-"));
}
switch (op) {
case '+':
result = dig0.add(dig1);
break;
case '-':
result = dig0.subtract(dig1);
break;
case '*':
result = dig0.multiply(dig1);
break;
case '/':
result = dig0.divide(dig1, MC);
break;
case '^':
result = new BigDecimal(Double.toString(Math.pow(dig0.doubleValue(), dig1.doubleValue())));
break;
case 's':
result = new BigDecimal(Double.toString(Math.sin(dig0.doubleValue())));
break;
case 'c':
result = new BigDecimal(Double.toString(Math.cos(dig0.doubleValue())));
break;
case 't':
result = new BigDecimal(Double.toString(Math.tan(dig0.doubleValue())));
break;
case 'l':
result = new BigDecimal(Double.toString(Math.log(dig0.doubleValue())));
break;
case 'L':
result = new BigDecimal(Double.toString(Math.log10(dig0.doubleValue())));
break;
default:
throw new RuntimeException(op + " operator is invalid for baseCal.");
}
return result.stripTrailingZeros().toPlainString().replace("-", "m");
}
static void check(StringBuilder buf) {
String msg = null;
String str = buf.toString();
if(buf.lastIndexOf("(") > buf.lastIndexOf(")") || count(buf, '(') != count(buf, ')')) {
msg = "括号没有匹配";
}
if(str.matches(".*?[0-9][(sctlL].*?")) {
msg = "数字不能紧跟左括号或函数";
}
if(str.matches(".*?[+\\-*/^(sctlL]\\).*?")) {
msg = "右括号前不能是运算符";
}
if(str.matches(".*?[sctlL][^(].*?")) {
msg = "函数参数必须由括号括起来";
}
if(str.matches("[^0-9]*?\\..*?|.*?\\.[^0-9]*?")) {
msg = "小数点前后必须是数字";
}
if(msg != null) {
throw new RuntimeException(msg);
}
}
static int count(StringBuilder buf, char c) {
int len = buf.length();
int sum = 0;
while(--len > -1) {
if(c == buf.charAt(len)) ++sum;
}
return sum;
}
}