// 文字列式微分エンジン // 1998 N.Inoue public class Differentiate{ /** * 与えられた関数の導関数を返す * @param str 関数 * @param c 文字 * @return 導関数 */ public static String differentiate(String str, char c) { return replace(differentiate(replace(str, c, 'x')), 'x', c); } private static boolean isLowerAlpha(char c) { if((c >= 'a')&&(c <= 'z')) return true; else return false; } private static String replace(String str, char fc, char tc) { int strlen = str.length(); StringBuffer strbuf = new StringBuffer(str); for(int i=0; i 0) { if(number == 1.0) result = "+" + substr.substring(1, substr.length()-1); else { if(substr.equals("(1)")) result = "+" + number; else result = "+" + number + "*" + substr; } } else { if(number == -1.0) result = "-" + substr.substring(1, substr.length()-1); else { if(substr.equals("(1)")) result = String.valueOf(number); else result = number + "*" + substr; } } //debug System.out.println("kou out=" + result ); return result; } private static String partsub(String part) { //debug System.out.println("part in=" + part); String result; String functionstr; String exponentstr; int strlen = part.length(); int strpos = strlen; int kdepth = 0; // 渡された部分を指数部分とその他の部分に分割 char chr; do { strpos--; if(strpos < 0) break; if((chr = part.charAt(strpos)) == ')') kdepth++; else if(chr == '(') kdepth--; }while ((chr != '^')||(kdepth != 0)); if(strpos < 0) { exponentstr = "1"; functionstr = part; } else { exponentstr = part.substring(strpos+1); functionstr = part.substring(0, strpos); } // 指数関数を微分して中の関数はfinalpartsubに渡す if(exponentstr.indexOf('x') == -1) { // a = f(x) // (a^n)' =a^(n-1) * n * a' int num; if((num = (int)Calc.calc(exponentstr)) == 1) result = finalpartsub(functionstr); else { if(num == 2) result = exponentstr + "*" + functionstr; else result = exponentstr + "*" + functionstr + "^(" + exponentstr + "-1)"; String difstr = finalpartsub(functionstr); if(!difstr.equals("1")) result += "*" + difstr; } } else { // a = f(x), b = g(x) // (a^b)' = a^b * b' * log a + b * a^(b-1) * a' String difstr = finalpartsub(exponentstr); if(difstr.equals("1")) result = part + "*log(" + functionstr + ")"; else result = part + "*" + difstr + "*log(" + functionstr + ")"; if(functionstr.indexOf('x') != -1) { String difstr_b = finalpartsub(functionstr); result = "(" + result; if(difstr_b.equals("1")) result += "+" + exponentstr + "*" + functionstr + "^(" + exponentstr + "-1))"; else result += "+" + exponentstr + "*" + functionstr + "^(" + exponentstr + "-1)*" + difstr_b + ")"; } } //debug System.out.println("part out="+result); return result; } private static String finalpartsub(String finalpart) { // finalpartsubに渡されるのは単一の関数 //debug System.out.println("finalpart in="+finalpart); // 特例 (x)' = 1 if(finalpart.equals("x")) { //debug System.out.println("finalpart out=1"); return "1"; } String result; String argstr; String difstr; int strpos; int strlen = finalpart.length(); int kdepth = 0; char chr; // 指数関数の場合はpartsubに渡す for(strpos = 0; strpos