-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunction.java
More file actions
691 lines (599 loc) · 22.9 KB
/
Copy pathFunction.java
File metadata and controls
691 lines (599 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// Function.java
package integrals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
/**
* Java class that models a function of x.
*
* <p>The following functions are supported:
* sin, cos, tan, csc, sec, cot, arcsin, arccos, arctan, ln, log, sinh, cosh, tanh, sqrt.
* Arguments are assumed to be in radians.</p>
*
* @author Ayesha Ilyas
* @since 3/25/22
* <p>Updated 4/11/22</p>
* <p>Updated 4/25/22</p>
* @version 1.3
*
*/
public class Function {
// * * * * * * * * * * * Private Attributes * * * * * * * * * * //
private final String[] validTokens = {"x", "e", "pi", "sin", "cos", "tan", "csc", "sec", "cot", "arcsin",
"arccos", "arctan", "ln", "log", "sinh", "cosh", "tanh", "sqrt"};
private List<String> originalTokens;
private String function;
// * * * * * * * * * * * Public Services * * * * * * * * * * //
/**
* Constructor creates a <code>Function</code> using the String passed as an argument.
*
* @param function a <code>String</code> representing the <code>Function</code>. x is assumed to be the function's variable.
* @throws IllegalArgumentException if <code>function</code> if not a valid function
*
*/
public Function(String function) {
// assumes variable is x
if (function.isEmpty())
throw new IllegalArgumentException("Input must be at least one character.");
originalTokens = tokenize(function); // may throw IllegalArgumentException
this.function = function.replace(" ", "");
}
/**
* Changes the function that the <code>Function</code> object represents.
*
* @param function a <code>String</code> representing the new function
* @throws IllegalArgumentException if the <code>function</code> if not valid
*/
public void setFunction(String function) {
// assumes variable is x
if (function.isEmpty())
throw new IllegalArgumentException("Input must be at least one character.");
originalTokens = tokenize(function);
this.function = function.replace(" ", "");
}
/**
* Returns a read-only list of tokens.
* @return an unmodifiable <code>List</code> of <code>String</code> objects
* @see java.util.Collections#unmodifiableList
*/
public List<String> getTokens() {
return Collections.unmodifiableList(originalTokens);
}
/**
* Gets the function <code>String</code>.
* @return a <code>String</code> representing the function.
*/
public String toString() {
return function;
}
// * * * * * * * * * * Public Parsing Methods * * * * * * * * * * //
/**
* Evaluates the function at a specified value and returns the result.
*
* @param value a <code>double</code> to evaluate the function at
* @return the value of the function at the specified number as a <code>double</code>
* @throws ArithmeticException if <code>value</code> if not in the domain
*
*/
public double evaluateAt(double value) {
return evaluateAt(value, false);
}
// The overloaded evaluateAt methods with String arguments evaluate expressions that
// don't contain variables.
/**
* Evaluates the function at a specified value and returns the result.
*
* <p>This method can be used to evaluate a function at a value that is itself an expression
* that does not contain variables such as pi, 3*pi/2, e/2.</p>
*
* @param value a <code>String</code> to evaluate the function at
* @return the value of the function at the specified number as a <code>double</code>
* @throws ArithmeticException if <code>value</code> if not in the domain
*
*/
public double evaluateAt(String value) {
return evaluateAt(value, false);
}
/**
* Evaluates the function at a specified value and returns the result.
*
* <p>This method can be used to evaluate a function at a value that is itself an expression
* that does not contain variables such as pi, 3*pi/2, e/2.</p>
*
* @param value a <code>String</code> to evaluate the function at
* @param verbose a <code>boolean</code> specifying whether to print out the steps involved in the evaluation.
* To show steps, use true.
* @return the value of the function at the specified number as a <code>double</code>
* @throws ArithmeticException if <code>value</code> if not in the domain
*
*/
public double evaluateAt(String value, boolean verbose) {
return evaluateAt(Function.evaluate(value), verbose);
}
/**
* A static method that evaluates a <code>String</code> expression and returns a <code>double</code> result.
* This method can be used to get the double equivalent of expressions like pi, 3*pi/2, and e/2.
*
* @param expression a <code>String</code> expression
* @return the <code>double</code> value of the expression
* @throws IllegalArgumentException if <code>expression</code> contains variables or expression is not more than one character in length
*
*/
// for constant functions and expressions without variables
public static double evaluate(String expression) {
// if value contains the variable, x, throw an error
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) == 'x')
throw new IllegalArgumentException("Expression must not contain variables.");
}
return new Function(expression).evaluateAt(0);
}
/**
* Evaluates the function at a specified value and returns the result.
*
* @param value a <code>double</code> to evaluate the function at
* @param verbose a <code>boolean</code> specifying whether to print out the steps involved in the evaluation.
* To show steps, use true.
* @return the value of the function at the specified number as a <code>double</code>
* @throws ArithmeticException if <code>value</code> if not in the domain
*
*/
public double evaluateAt(double value, boolean verbose) {
// create copy of originalTokens
List<String> tokens = new ArrayList<>();
for (int i = 0; i < originalTokens.size(); i++) {
tokens.add("0");
}
Collections.copy(tokens, originalTokens);
// replace all x with value
for (int i = 0; i < tokens.size(); i++) {
if (tokens.get(i).equals("x"))
tokens.set(i, String.valueOf(value));
}
// print function with x subbed for value
if (verbose) {
StringBuilder output = new StringBuilder(String.format("%nf(%.4f) = ", value));
output.append(getString(tokens));
System.out.printf("%s%n", output);
}
while (tokens.size() > 1) {
parse(getInnermostExpression(tokens));
if (verbose) {
StringBuilder output = new StringBuilder(" = ");
output.append(getString(tokens));
System.out.printf("%s%n", output);
}
}
return parseNumber(tokens.get(0));
}
// * * * * * * * * * * * Private Parsing Methods * * * * * * * * * * * //
private String getString(List<String> tokens) {
StringBuilder formattedString = new StringBuilder();
for (String token : tokens) {
if (!token.matches("e|pi|x") && isNumber(token))
formattedString.append(String.format("%.4f", Double.parseDouble(token)));
else
formattedString.append(token);
}
return formattedString.toString();
}
private void parse(List<String> tokens) {
// exponentiation
resolveExponentiation(tokens);
// transcendental functions
resolveFunctions(tokens);
// mult and div
resolveMultAndDiv(tokens);
// addition and subtraction
resolveAddAndSub(tokens);
// for values that fall through function calls, like e and pi
tokens.set(0, String.valueOf(parseNumber(tokens.get(0))));
}
// throws NumberFormatException if not parsable into a double
private double parseNumber(String number) {
double operand;
if (number.equals("e")) {
operand = Math.E;
} else if (number.equals("pi")) {
operand = Math.PI;
} else {
operand = Double.parseDouble(number); // throws NumberFormatException
}
return operand;
}
private double enhancedSin(double argument) {
// return 0 for all multiples of pi and sin(argument) otherwise
return argument % Math.PI == 0 ? 0 : Math.sin(argument);
}
private double enhancedCos(double argument) {
// return 0 for all odd multiples of pi/2 and cos(argument) otherwise
return ((argument % (Math.PI / 2) == 0) && !(argument / (Math.PI / 2) % 2 == 0)) ? 0 : Math.cos(argument);
}
// sin, cos, tan, csc, sec, cot, arcsin, arccos, arctan, ln, log, sinh, cosh, tanh, sqrt
// arguments in radians
// Assumes that the element after the function name is the argument to function and attempts to calculate
// with that argument. If the argument is NaN, then a NumberFormatException is caught and the program continues executing.
// throws ArithmeticException if number is not in domain of function or division by zero
private void resolveFunctions(List<String> tokens) {
ListIterator<String> iterator = tokens.listIterator();
if (tokens.size() == 1)
return;
// calculate function values
while (iterator.hasNext()) {
try {
// get current index
int i = iterator.previousIndex() + 1;
// return if last element is reached
if (i == tokens.size() - 1)
return;
String token = tokens.get(i); // get token at current index
// gets next token and converts to double if possible or throws a NumberFormatException
double number = parseNumber(tokens.get(i + 1));
double result = 0; // value will be overwritten when needed
// sin, cos, tan, csc, sec, cot
if (token.equals("sin"))
result = enhancedSin(number);
else if (token.equals("cos"))
result = enhancedCos(number);
else if (token.equals("tan"))
result = enhancedSin(number) / enhancedCos(number);
else if (token.equals("csc"))
result = 1 / enhancedSin(number);
else if (token.equals("sec"))
result = 1 / enhancedCos(number);
else if (token.equals("cot"))
result = enhancedCos(number) / enhancedSin(number);
// arcsin, arccos, arctan
else if (token.equals("arcsin"))
result = Math.asin(number);
else if (token.equals("arccos"))
result = Math.acos(number);
else if (token.equals("arctan"))
result = Math.atan(number);
// log, ln
else if (token.equals("ln"))
result = Math.log(number);
else if (token.equals("log"))
result = Math.log10(number);
// sinh, cosh, tan
else if (token.equals("sinh"))
result = Math.sinh(number);
else if (token.equals("cosh"))
result = Math.cosh(number);
else if (token.equals("tanh"))
result = Math.tanh(number);
// sqrt
else if (token.equals("sqrt"))
result = Math.sqrt(number);
if (token.matches("sin|cos|tan|csc|sec|cot|arcsin|arccos|arctan|ln|log|sinh|cosh|tanh|sqrt")) {
// if the number is not in the domain, then the result will either be NaN or +/- infinity
if (Double.isNaN(result) || Double.isInfinite(result))
throw new ArithmeticException(String.format("%.4f not in domain", number));
// set value to the left of operand to result
tokens.set(i, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.next();
iterator.remove();
iterator.previous();
}
// advance iterator
iterator.next();
} catch (NumberFormatException e) {
iterator.next();
}
}
}
private void resolveExponentiation(List<String> tokens) {
ListIterator<String> iterator = tokens.listIterator();
// exponentiation
while (iterator.hasNext()) {
// get current index
int i = iterator.previousIndex() + 1;
if (tokens.get(i).equals("^")) {
double result = Math.pow(parseNumber(tokens.get(i - 1)), parseNumber(tokens.get(i + 1)));
// set value to the left of operand to result
tokens.set(i - 1, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.remove();
iterator.next();
iterator.remove();
iterator.previous();
}
// advance iterator
iterator.next();
}
}
private void resolveMultAndDiv(List<String> tokens) {
ListIterator<String> iterator = tokens.listIterator();
// mult and div
while (iterator.hasNext()) {
// get current index
int i = iterator.previousIndex() + 1;
if (tokens.get(i).equals("*")) {
double result = parseNumber(tokens.get(i - 1)) * parseNumber(tokens.get(i + 1));
// set value to the left of operand to result
tokens.set(i - 1, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.remove();
iterator.next();
iterator.remove();
iterator.previous();
}
else if (tokens.get(i).equals("/")) {
double result = parseNumber(tokens.get(i - 1)) / parseNumber(tokens.get(i + 1));
if (Double.isInfinite(result) || Double.isNaN(result))
throw new ArithmeticException(String.format("%s not in domain", tokens.get(i + 1)));
// set value to the left of operand to result
tokens.set(i - 1, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.remove();
iterator.next();
iterator.remove();
iterator.previous();
}
// advance iterator
iterator.next();
}
}
private void resolveAddAndSub(List<String> tokens) {
ListIterator<String> iterator = tokens.listIterator();
while (iterator.hasNext()) {
// get current index
int i = iterator.previousIndex() + 1;
if (tokens.get(i).equals("+")) {
double result = parseNumber(tokens.get(i - 1)) + parseNumber(tokens.get(i + 1));
// set value to the left of operand to result
tokens.set(i - 1, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.remove();
iterator.next();
iterator.remove();
iterator.previous();
}
else if (tokens.get(i).equals("-")) {
double result = parseNumber(tokens.get(i - 1)) - parseNumber(tokens.get(i + 1));
// set value to the left of operand to result
tokens.set(i - 1, String.valueOf(result));
// delete current and next item
iterator.next();
iterator.remove();
iterator.next();
iterator.remove();
iterator.previous();
}
// advance iterator
iterator.next();
}
}
// get the right innermost expression
// to get the left innermost expression, you can use a recursive solution
// but it's much slower
private List<String> getInnermostExpression(List<String> tokens) {
int startParenIndex = tokens.lastIndexOf("(");
if (startParenIndex == -1) return tokens;
int endParenIndex = -1;
for (int i = startParenIndex; i < tokens.size(); i++) {
if (tokens.get(i).equals(")")) {
endParenIndex = i;
break;
}
}
if (endParenIndex == -1) return tokens;
// delete parens from list and return what was in the parens
List<String> sublist = tokens.subList(startParenIndex, endParenIndex + 1);
sublist.remove(0);
sublist.remove(sublist.size() - 1);
return sublist;
}
// * * * * * * * * * * Tokenizing Methods * * * * * * * * * * //
private List<String> tokenize(String function) {
// remove spaces
function = function.replace(" ", "");
// create empty list
List<String> tokens = new ArrayList<>();
function = checkPreconditions(function, tokens); // throws IllegalArgumentException
// keeps track of series of characters in order to match tokens such as sin, cos, pi, etc...
String token = "";
for (int i = 0; i < function.length(); i++) {
token += function.charAt(i);
// handles the case that the current char is an operator
if (isOperator(function.charAt(i))) {
// see if token is a number and add to list if it is
// take substring from beginning to second to last character, because the last character is an operator
String potentialNumber = token.substring(0, token.length() - 1); // if token has length 1, potentialNumber will be ""
if (isNumber(potentialNumber)) {
// if there was ), variable, pi, or e before the number, add a multiplication symbol before the number
if (!tokens.isEmpty() && (tokens.get(tokens.size() - 1).equals(")") ||
isNumber(tokens.get(tokens.size() - 1))))
tokens.add("*");
// after this step, token will contain just the operator
token = String.valueOf(token.charAt(token.length() - 1));
tokens.add(potentialNumber);
} else if (!potentialNumber.isEmpty()) {
// if token is invalid throw an exception
// check to see if any part of the token is valid
// need for cases where a number like pi or e is being multiplied by another number
// without being explicitly separated by a multiplication symbol
String numericPart = "";
String nonNumericPart = "";
for (int index = 0; index < token.length(); index++) {
if (!(Character.isDigit(token.charAt(index)) || token.charAt(index) == '.')) {
numericPart = token.substring(0, index);
nonNumericPart = function.substring(i - (token.length() - 1 - index));
break;
}
}
if (isNumber(numericPart)) {
tokens.add(numericPart);
tokens.add("*");
// move to a previous position in the string
i = function.length() - nonNumericPart.length() - 1;
// reset token
token = "";
continue;
} else
throw new IllegalArgumentException(String.format("Unknown token \"%s\" in expression.", potentialNumber));
}
// if the current character is an operator or paren, add it to list
if (i > 0) { // i needs to be 1 or more since the character at i-1 is accessed
char current = function.charAt(i);
char previous = function.charAt(i - 1);
String lastToken = tokens.get(tokens.size() - 1);
// insert * between expression being multiplied together like this (expression1)(expression2) or
// number(expression)
if (current == '(' && (previous == ')' || isNumber(lastToken)))
tokens.add("*");
// insert * for expression of the form (expression)number
else if (current == ')' && (i + 1) < function.length() && isNumber(String.valueOf(function.charAt(i + 1)))) {
tokens.add(")");
tokens.add("*");
token = "";
}
// replace minus signs by -1 *
else if (current == '-' && previous == '(') {
tokens.add("-1");
tokens.add("*");
token = "";
}
// throw exception if there are operators other than ( after a function name
else if (!tokens.isEmpty() && current != '(' && !isNumber(lastToken) &&
isValidToken(lastToken))
throw new IllegalArgumentException("Illegal character after function name.");
// throw error if there are invalid consecutive operators
// for ex: ^), **, *^, (/
else if (isOperator(previous) && !(previous == ')' || current == '('))
throw new IllegalArgumentException("Consecutive operators not allowed.");
}
// add operator if it has not already been added
if (!token.isEmpty())
tokens.add(token);
// reset token
token = "";
}
// add any valid token to list; see isValidToken
// assumes that x is the function parameter
else if (isValidToken(token)) {
// if token is sin, cos, or tan check to see if next char is h -> hyperbolic
// skip to next iteration in case of hyperbolic functions
if (token.matches("sin|cos|tan") && (i + 1) < function.length() && function.charAt(i + 1) == 'h')
continue;
// if there is ) before the token, add a multiplication symbol before the token
// if there is an x, e, pi, or # before token, insert *
if (!tokens.isEmpty() && (tokens.get(tokens.size() - 1).equals(")") ||
isNumber(tokens.get(tokens.size() - 1))))
tokens.add("*");
tokens.add(token);
// reset token
token = "";
}
}
// check to see if there is a trailing number stored in token
if (isNumber(token)) {
if (!tokens.isEmpty() && (tokens.get(tokens.size() - 1).equals(")") ||
isNumber(tokens.get(tokens.size() - 1))))
tokens.add("*");
tokens.add(token);
}
else if (!token.isEmpty()) {
String numericPart = "";
String nonNumericPart = "";
for (int index = 0; index < token.length(); index++) {
if (!(Character.isDigit(token.charAt(index)) || token.charAt(index) == '.')) {
numericPart = token.substring(0, index);
nonNumericPart = token.substring(index);
break;
}
}
if (isNumber(numericPart)) {
tokens.add(numericPart);
tokens.add("*");
// recursive tokenizing
tokens.addAll(tokenize(nonNumericPart)); // throws IllegalArgumentException
} else
throw new IllegalArgumentException(String.format("Unknown token \"%s\" in expression.", token));
}
// throw error if last token is not a ), a number, or x
String lastToken = tokens.get(tokens.size() - 1);
if (!(lastToken.equals(")") || isNumber(lastToken)))
throw new IllegalArgumentException("Invalid ending token.");
return tokens;
}
private int frequency(String s, char c) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
count++;
}
return count;
}
private String checkPreconditions(String function, List<String> tokens) {
// check to see if parens match (i.e. for every opening paren, there is a closing paren
if (frequency(function, ')') != frequency(function, '('))
throw new IllegalArgumentException("Unmatching parenthesis.");
// Make sure leading characters are valid before parsing
if (function.length() == 1 && !isNumber(String.valueOf(function.charAt(0)))) {
throw new IllegalArgumentException(String.format("Unknown token \"%s\" in expression.", function));
}
else if (function.length() >= 2) {
char first = function.charAt(0);
char second = function.charAt(1);
// replace leading negative sign followed by x, a number, or valid token (any function name)
// with -1 * and remove the sign
if (first == '-') {
if (isNumber(String.valueOf(second)) || containsValidToken(function, 1)) {
tokens.add("-1");
tokens.add("*");
function = function.replaceFirst("-", "");
}
}
// if there is a single leading plus sign followed by x, a digit, or function name, remove the sign
else if (first == '+' && (second == 'x' || Character.isDigit(second) || containsValidToken(function, 1)))
function = function.replaceFirst("\\+", "");
// throw error if the first character is an operator not equal to + / - followed by x or digit
// Ex: throws when ++, --, **, *x
else if (!(first == '(') && isOperator(first))
throw new IllegalArgumentException("Invalid leading token.");
}
return function;
}
private boolean isOperator(char c) {
char[] tokens = {'^', '*', '/', '+', '-', '(', ')'};
for (char token : tokens) {
if (c == token)
return true;
}
return false;
}
private boolean isValidToken(String s) {
for (String token : validTokens) {
if (s.equals(token))
return true;
}
return false;
}
private boolean containsValidToken(String s, int startIndex) {
for (String token: validTokens) {
if (s.substring(startIndex).length() >= token.length()
&& s.substring(startIndex, startIndex + token.length()).equals(token)) {
return true;
}
}
return false;
}
private boolean isNumber(String s) {
if (s.equals("e") || s.equals("pi") || s.equals("x"))
return true;
try {
Double.parseDouble(s); // if parseDouble does not throw an error, it is a valid double
return true;
} catch (NumberFormatException e) {
return false;
}
}
}