Example #1
0
  public static void main(String[] args) {

    while (true) {
      System.out.println("\n\nEnter an expression, or press return to end.");
      System.out.print("\n?  ");
      TextIO.skipBlanks();
      if (TextIO.peek() == '\n') break;
      try {
        ExpNode exp = expressionTree();
        TextIO.skipBlanks();
        if (TextIO.peek() != '\n') throw new ParseError("Extra data after end of expression.");
        TextIO.getln();
        ExpNode deriv = exp.derivative();
        System.out.println("\nA fully parenthesized expression for the derivative is:");
        System.out.print("   ");
        deriv.printInfix();
        System.out.println();
        System.out.println("\nValue of derivative at x = 0 is " + deriv.value(0));
        System.out.println("Value of derivative at x = 1 is " + deriv.value(1));
        System.out.println("Value of derivative at x = 2 is " + deriv.value(2));
        System.out.println("Value of derivative at x = 3 is " + deriv.value(3));
        System.out.println("\nOrder of postfix evaluation for derivative is:\n");
        deriv.printStackCommands();
      } catch (ParseError e) {
        System.out.println("\n*** Error in input:    " + e.getMessage());
        System.out.println("*** Discarding input:  " + TextIO.getln());
      }
    }

    System.out.println("\n\nDone.");
  } // end main()
Example #2
0
 ExpNode derivative() {
   // Apply the derivative formulas.
   switch (op) {
     case '+':
       return new BinOpNode('+', left.derivative(), right.derivative());
     case '-':
       return new BinOpNode('-', left.derivative(), right.derivative());
     case '*':
       return new BinOpNode(
           '+',
           new BinOpNode('*', left, right.derivative()),
           new BinOpNode('*', right, left.derivative()));
     case '/':
       return new BinOpNode(
           '/',
           new BinOpNode(
               '-',
               new BinOpNode('*', right, left.derivative()),
               new BinOpNode('*', left, right.derivative())),
           new BinOpNode('*', right, right));
     default:
       return null;
   }
 }
Example #3
0
 ExpNode derivative() {
   // The derivative of -A is -(derivative of A).
   return new UnaryMinusNode(operand.derivative());
 }