1
0
mirror of https://github.com/DanilaFe/abacus synced 2026-01-25 16:15:19 +00:00

Compare commits

...

26 Commits

Author SHA1 Message Date
Arthur Drobot
1e6cf08ec2 Write arctan and add arccot. 2017-08-11 01:19:13 -07:00
Arthur Drobot
fee9f091fd Revert "Write a RationalNumber class."
This reverts commit f3942b6760.
2017-08-09 18:43:52 -07:00
Arthur Drobot
4226df72f5 Add arcsec. Adjust some comments. 2017-08-09 16:04:26 -07:00
Arthur Drobot
1f0e6a7ce4 Add arccsc. 2017-08-09 15:57:02 -07:00
Arthur Drobot
efe76a6fdc Add arccos. 2017-08-09 15:08:54 -07:00
Arthur Drobot
ca6d8d2ba2 Add arcsin. 2017-08-09 12:47:43 -07:00
Arthur Drobot
1d6957c4d9 Write a RationalNumber class. 2017-08-08 14:53:34 -07:00
Arthur Drobot
b6e4c6d2ea Merge branch 'sig-fig' 2017-08-08 09:46:46 -07:00
Arthur Drobot
f8b3559cec Add some tests to pow. 2017-08-08 09:45:13 -07:00
Arthur Drobot
4cf4ba98a8 Adjust unit tests. Set the number of significant figures in the output to 50. 2017-08-08 09:27:10 -07:00
12710c625b Add missing comments. 2017-08-07 22:48:56 -07:00
e71b037195 Switch the ToggleablePlugin class to Kotlin to avoid boilerplate. 2017-08-07 22:44:16 -07:00
fe92929856 Switch HistoryModel to Kotlin to avoid boilerplate. 2017-08-07 22:39:35 -07:00
ff7d90967e Fix toString errors failing unit tests. 2017-08-07 19:22:35 -07:00
355a91d690 Rewrite the Operator in Kotlin. 2017-08-07 19:16:51 -07:00
5f0fba15eb Add comments to the newly created Kotlin implementations. 2017-08-07 19:11:13 -07:00
3bdc0e2ae5 Rewrite tree nodes in Kotlin. Documentation pending. 2017-08-07 18:57:43 -07:00
Arthur Drobot
68fbcd2d7c Modify exp to use the non-alternating series and take a reciprocal in the case of a negative argument. 2017-08-07 18:13:18 -07:00
Arthur Drobot
ed92b382f0 Rewrite precise number to limit significant figures rather than decimal places. Add getMaxError to NumberInterface; modify numbers and StandardPlugin appropriately. 2017-08-07 17:58:18 -07:00
e54b5cdd66 Add Kotlin support to gradle. 2017-08-07 17:33:56 -07:00
fd87cb66a3 Merge branch 'master' of github.com:DanilaFe/abacus 2017-08-07 14:27:29 -07:00
Arthur Drobot
1cd544e712 Merge branch 'master' of https://github.com/DanilaFe/abacus 2017-08-07 14:08:17 -07:00
Arthur Drobot
a8c70a6bbe Add checking of negative bases raised to non-integer powers in matchesParams in OP_CARET. 2017-08-07 14:05:15 -07:00
Arthur Drobot
8a9df051cf Optimize pow for integer bases. 2017-08-07 13:43:12 -07:00
Arthur Drobot
4eda15b3fb Modify some functions in PreciseNumber for consistency. 2017-08-07 13:41:45 -07:00
Arthur Drobot
d0ccb8b625 Improve some comments of NumberInterface functions. 2017-08-07 10:54:27 -07:00
23 changed files with 434 additions and 603 deletions

View File

@@ -1,3 +1,8 @@
plugins {
id 'java'
id 'application'
id 'org.jetbrains.kotlin.jvm' version '1.1.3'
}
apply plugin: 'java'
apply plugin: 'application'
@@ -7,6 +12,7 @@ repositories {
dependencies {
compile 'com.moandjiezana.toml:toml4j:0.7.1'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
testCompile 'junit:junit:4.12'
}

View File

@@ -1,76 +0,0 @@
package org.nwapw.abacus.function;
/**
* A class that represents a single infix operator.
*/
public class Operator {
/**
* The associativity of the operator.
*/
private OperatorAssociativity associativity;
/**
* The type of this operator.
*/
private OperatorType type;
/**
* The precedence of the operator.
*/
private int precedence;
/**
* The function that is called by this operator.
*/
private Function function;
/**
* Creates a new operator with the given parameters.
*
* @param associativity the associativity of the operator.
* @param operatorType the type of this operator, like binary infix or unary postfix.
* @param precedence the precedence of the operator.
* @param function the function that the operator calls.
*/
public Operator(OperatorAssociativity associativity, OperatorType operatorType, int precedence, Function function) {
this.associativity = associativity;
this.type = operatorType;
this.precedence = precedence;
this.function = function;
}
/**
* Gets the operator's associativity.
*
* @return the associativity.
*/
public OperatorAssociativity getAssociativity() {
return associativity;
}
/**
* Gets the operator's type.
*
* @return the type.
*/
public OperatorType getType() {
return type;
}
/**
* Gets the operator's precedence.
*
* @return the precedence.
*/
public int getPrecedence() {
return precedence;
}
/**
* Gets the operator's function.
*
* @return the function.
*/
public Function getFunction() {
return function;
}
}

View File

@@ -216,7 +216,7 @@ public class AbacusController implements PluginListener {
Callback<TableColumn<HistoryModel, String>, TableCell<HistoryModel, String>> cellFactory =
param -> new CopyableCell<>();
Callback<ListView<ToggleablePlugin>, ListCell<ToggleablePlugin>> pluginCellFactory =
param -> new CheckBoxListCell<>(ToggleablePlugin::enabledProperty, new StringConverter<ToggleablePlugin>() {
param -> new CheckBoxListCell<>(ToggleablePlugin::getEnabledProperty, new StringConverter<ToggleablePlugin>() {
@Override
public String toString(ToggleablePlugin object) {
return object.getClassName().substring(object.getClassName().lastIndexOf('.') + 1);
@@ -224,7 +224,7 @@ public class AbacusController implements PluginListener {
@Override
public ToggleablePlugin fromString(String string) {
return new ToggleablePlugin(true, string);
return new ToggleablePlugin(string, true);
}
});
@@ -243,11 +243,11 @@ public class AbacusController implements PluginListener {
enabledPluginView.setItems(enabledPlugins);
enabledPluginView.setCellFactory(pluginCellFactory);
inputColumn.setCellFactory(cellFactory);
inputColumn.setCellValueFactory(cell -> cell.getValue().inputProperty());
inputColumn.setCellValueFactory(cell -> cell.getValue().getInputProperty());
parsedColumn.setCellFactory(cellFactory);
parsedColumn.setCellValueFactory(cell -> cell.getValue().parsedProperty());
parsedColumn.setCellValueFactory(cell -> cell.getValue().getParsedProperty());
outputColumn.setCellFactory(cellFactory);
outputColumn.setCellValueFactory(cell -> cell.getValue().outputProperty());
outputColumn.setCellValueFactory(cell -> cell.getValue().getOutputProperty());
coreTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (oldValue.equals(settingsTab)) alertIfApplyNeeded(true);
});
@@ -343,8 +343,8 @@ public class AbacusController implements PluginListener {
numberImplementationBox.getSelectionModel().select(toSelect);
for (Class<?> pluginClass : abacus.getPluginManager().getLoadedPluginClasses()) {
String fullName = pluginClass.getName();
ToggleablePlugin plugin = new ToggleablePlugin(!disabledPlugins.contains(fullName), fullName);
plugin.enabledProperty().addListener(e -> changesMade = true);
ToggleablePlugin plugin = new ToggleablePlugin(fullName, !disabledPlugins.contains(fullName));
plugin.getEnabledProperty().addListener(e -> changesMade = true);
enabledPlugins.add(plugin);
}
functionList.addAll(manager.getAllFunctions());

View File

@@ -1,97 +0,0 @@
package org.nwapw.abacus.fx;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* The data model used for storing history entries.
*/
public class HistoryModel {
/**
* The property used for displaying the column
* for the user input.
*/
private final StringProperty input;
/**
* The property used for displaying the column
* that contains the parsed input.
*/
private final StringProperty parsed;
/**
* The property used for displaying the column
* that contains the program output.
*/
private final StringProperty output;
/**
* Creates a new history model with the given variables.
*
* @param input the user input
* @param parsed the parsed input
* @param output the program output.
*/
public HistoryModel(String input, String parsed, String output) {
this.input = new SimpleStringProperty();
this.parsed = new SimpleStringProperty();
this.output = new SimpleStringProperty();
this.input.setValue(input);
this.parsed.setValue(parsed);
this.output.setValue(output);
}
/**
* Gets the input property.
*
* @return the input property.
*/
public StringProperty inputProperty() {
return input;
}
/**
* Gets the input.
*
* @return the input.
*/
public String getInput() {
return input.get();
}
/**
* Gets the parsed input property.
*
* @return the parsed input property.
*/
public StringProperty parsedProperty() {
return parsed;
}
/**
* Gets the parsed input.
*
* @return the parsed input.
*/
public String getParsed() {
return parsed.get();
}
/**
* Gets the output property.
*
* @return the output property.
*/
public StringProperty outputProperty() {
return output;
}
/**
* Gets the program output.
*
* @return the output.
*/
public String getOutput() {
return output.get();
}
}

View File

@@ -1,60 +0,0 @@
package org.nwapw.abacus.fx;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
/**
* Class that represents an entry in the plugin check box list.
* The changes from this property are written to the config on application.
*/
public class ToggleablePlugin {
/**
* The property that determines whether the plugin will be enabled.
*/
private final BooleanProperty enabled;
/**
* The name of the class this entry toggles.
*/
private final String className;
/**
* Creates a new toggleable plugin with the given properties.
*
* @param enabled the enabled / disabled state at the beginning.
* @param className the name of the class this plugin toggles.
*/
public ToggleablePlugin(boolean enabled, String className) {
this.enabled = new SimpleBooleanProperty();
this.enabled.setValue(enabled);
this.className = className;
}
/**
* Gets the enabled property of this plugin.
*
* @return the enabled property.
*/
public BooleanProperty enabledProperty() {
return enabled;
}
/**
* Checks if this plugin entry should be enabled.
*
* @return whether this plugin will be enabled.
*/
public boolean isEnabled() {
return enabled.get();
}
/**
* Gets the class name this plugin toggles.
*
* @return the class name that should be disabled.
*/
public String getClassName() {
return className;
}
}

View File

@@ -128,5 +128,9 @@ public class NaiveNumber extends NumberInterface {
return Double.toString(Math.round(value * shiftBy) / shiftBy);
}
@Override
public NumberInterface getMaxError(){
return new NaiveNumber(Math.pow(10, -18));
}
}

View File

@@ -182,7 +182,7 @@ public abstract class NumberInterface {
* Also, checks if the thread has been interrupted, and if so, throws
* an exception.
*
* @return the least integer bigger or equal to the number, if int can hold the value.
* @return the least integer bigger or equal to the number.
*/
public final NumberInterface ceiling(){
checkInterrupted();
@@ -192,7 +192,7 @@ public abstract class NumberInterface {
/**
* Return the greatest integer less than or equal to the number.
*
* @return the greatest integer smaller or equal the number, if int can hold the value.
* @return the greatest integer smaller or equal the number.
*/
protected abstract NumberInterface floorInternal();
@@ -201,7 +201,7 @@ public abstract class NumberInterface {
* Also, checks if the thread has been interrupted, and if so, throws
* an exception.
*
* @return the greatest int smaller or equal to the number, if int can hold the value.
* @return the greatest int smaller than or equal to the number.
*/
public final NumberInterface floor(){
checkInterrupted();
@@ -216,7 +216,7 @@ public abstract class NumberInterface {
protected abstract NumberInterface fractionalPartInternal();
/**
* Returns the fractional part of the number.
* Returns the fractional part of the number, specifically x - floor(x).
* Also, checks if the thread has been interrupted,
* and if so, throws an exception.
* @return the fractional part of the number.
@@ -255,4 +255,11 @@ public abstract class NumberInterface {
return promoteToInternal(toClass);
}
/**
* Returns the smallest error this instance can tolerate depending
* on its precision and value.
* @return the smallest error that should be permitted in calculations.
*/
public abstract NumberInterface getMaxError();
}

View File

@@ -1,7 +1,7 @@
package org.nwapw.abacus.number;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.math.MathContext;
/**
* A number that uses a BigDecimal to store its value,
@@ -22,6 +22,21 @@ public class PreciseNumber extends NumberInterface {
*/
public static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
/**
* The number of extra significant figures kept in calculations before rounding for output.
*/
private static int numExtraInternalSigFigs = 15;
/**
* MathContext that is used when rounding a number prior to output.
*/
private static MathContext outputContext = new MathContext(50);
/**
* MathContext that is actually used in calculations.
*/
private static MathContext internalContext = new MathContext(outputContext.getPrecision()+numExtraInternalSigFigs);
/**
* The value of the PreciseNumber.
*/
@@ -48,7 +63,7 @@ public class PreciseNumber extends NumberInterface {
@Override
public int getMaxPrecision() {
return 65;
return internalContext.getPrecision();
}
@Override
@@ -58,7 +73,7 @@ public class PreciseNumber extends NumberInterface {
@Override
public NumberInterface divideInternal(NumberInterface divisor) {
return new PreciseNumber(value.divide(((PreciseNumber) divisor).value, this.getMaxPrecision(), RoundingMode.HALF_UP));
return new PreciseNumber(value.divide(((PreciseNumber) divisor).value, internalContext));
}
@Override
@@ -113,19 +128,18 @@ public class PreciseNumber extends NumberInterface {
String str = value.toPlainString();
int decimalIndex = str.indexOf('.');
if (decimalIndex != -1) {
return new PreciseNumber(str.substring(0, decimalIndex));
NumberInterface floor = new PreciseNumber(str.substring(0, decimalIndex));
if(signum() == -1){
floor = floor.subtract(ONE);
}
return floor;
}
return this;
}
@Override
public NumberInterface fractionalPartInternal() {
String str = value.toPlainString();
int decimalIndex = str.indexOf('.');
if (decimalIndex != -1) {
return new PreciseNumber(str.substring(decimalIndex + 1));
}
return ZERO;
return this.subtractInternal(floorInternal());
}
@Override
@@ -148,7 +162,11 @@ public class PreciseNumber extends NumberInterface {
@Override
public String toString() {
BigDecimal rounded = value.setScale(getMaxPrecision() - 15, RoundingMode.HALF_UP);
return rounded.stripTrailingZeros().toPlainString();
return value.round(outputContext).toString();
}
@Override
public NumberInterface getMaxError(){
return new PreciseNumber(value.ulp()).multiplyInternal(TEN.intPowInternal(value.precision()-internalContext.getPrecision()));
}
}

View File

@@ -188,7 +188,7 @@ public class StandardPlugin extends Plugin {
*/
private NumberInterface getLogPartialSum(NumberInterface x) {
NumberInterface maxError = getMaxError(x);
NumberInterface maxError = x.getMaxError();
x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClass())); //Terms used are for log(x+1).
NumberInterface currentNumerator = x, currentTerm = x, sum = x;
int n = 1;
@@ -207,7 +207,7 @@ public class StandardPlugin extends Plugin {
* @return the value of log(2) with the appropriate precision.
*/
private NumberInterface getLog2(NumberInterface number) {
NumberInterface maxError = getMaxError(number);
NumberInterface maxError = number.getMaxError();
//NumberInterface errorBound = fromInt(number.getClass(), 1);
//We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n)
//In the following, a=1/3^n, b=1/4^n, c = 1/n.
@@ -301,16 +301,11 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface maxError = getMaxError(params[0]);
NumberInterface maxError = params[0].getMaxError();
int n = 0;
if (params[0].signum() <= 0) {
NumberInterface currentTerm = NaiveNumber.ONE.promoteTo(params[0].getClass()), sum = currentTerm;
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) {
n++;
currentTerm = currentTerm.multiply(params[0]).divide((new NaiveNumber(n)).promoteTo(params[0].getClass()));
sum = sum.add(currentTerm);
}
return sum;
if (params[0].signum() < 0) {
NumberInterface[] negatedParams = {params[0].negate()};
return fromInt(params[0].getClass(), 1).divide(applyInternal(negatedParams));
} else {
//We need n such that x^(n+1) * 3^ceil(x) <= maxError * (n+1)!.
//right and left refer to lhs and rhs in the above inequality.
@@ -340,7 +335,8 @@ public class StandardPlugin extends Plugin {
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2
&& !(params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0
&& params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) == 0);
&& params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) == 0)
&& !(params[0].signum() == -1 && params[1].fractionalPart().compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) != 0);
}
@Override
@@ -349,6 +345,13 @@ public class StandardPlugin extends Plugin {
return NaiveNumber.ZERO.promoteTo(params[0].getClass());
else if (params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0)
return NaiveNumber.ONE.promoteTo(params[1].getClass());
//Detect integer bases:
if(params[0].fractionalPart().compareTo(fromInt(params[0].getClass(), 0)) == 0
&& FUNCTION_ABS.apply(params[1]).compareTo(fromInt(params[0].getClass(), Integer.MAX_VALUE)) < 0
&& FUNCTION_ABS.apply(params[1]).compareTo(fromInt(params[1].getClass(), 1)) >= 0){
NumberInterface[] newParams = {params[0], params[1].fractionalPart()};
return params[0].intPow(params[1].floor().intValue()).multiply(applyInternal(newParams));
}
return FUNCTION_EXP.apply(FUNCTION_LN.apply(FUNCTION_ABS.apply(params[0])).multiply(params[1]));
}
});
@@ -448,6 +451,144 @@ public class StandardPlugin extends Plugin {
}
};
/**
* The arcsine function (return type in radians).
*/
public final Function functionArcsin = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1
&& FUNCTION_ABS.apply(params[0]).compareTo(fromInt(params[0].getClass(), 1)) <= 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(FUNCTION_ABS.apply(params[0]).compareTo(new NaiveNumber(0.8).promoteTo(params[0].getClass())) >= 0){
NumberInterface[] newParams = {FUNCTION_SQRT.apply(fromInt(params[0].getClass(), 1).subtract(params[0].multiply(params[0])))};
return piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 2))
.subtract(applyInternal(newParams)).multiply(fromInt(params[0].getClass(), params[0].signum()));
}
NumberInterface currentTerm = params[0], sum = currentTerm,
multiplier = currentTerm.multiply(currentTerm), summandBound = sum.getMaxError().multiply(fromInt(sum.getClass(), 1).subtract(multiplier)),
power = currentTerm, coefficient = fromInt(params[0].getClass(), 1);
int exponent = 1;
while(FUNCTION_ABS.apply(currentTerm).compareTo(summandBound) > 0){
exponent += 2;
power = power.multiply(multiplier);
coefficient = coefficient.multiply(fromInt(params[0].getClass(), exponent-2))
.divide(fromInt(params[0].getClass(), exponent - 1));
currentTerm = power.multiply(coefficient).divide(fromInt(power.getClass(), exponent));
sum = sum.add(currentTerm);
}
return sum;
}
};
/**
* The arccosine function.
*/
public final Function functionArccos = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 && FUNCTION_ABS.apply(params[0]).compareTo(fromInt(params[0].getClass(), 1)) <= 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 2))
.subtract(functionArcsin.apply(params));
}
};
/**
* The arccosecant function.
*/
public final Function functionArccsc = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 && FUNCTION_ABS.apply(params[0]).compareTo(fromInt(params[0].getClass(), 1)) >= 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface[] reciprocalParamArr = {fromInt(params[0].getClass(), 1).divide(params[0])};
return functionArcsin.apply(reciprocalParamArr);
}
};
/**
* The arcsecant function.
*/
public final Function functionArcsec = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 && FUNCTION_ABS.apply(params[0]).compareTo(fromInt(params[0].getClass(), 1)) >= 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface[] reciprocalParamArr = {fromInt(params[0].getClass(), 1).divide(params[0])};
return functionArccos.apply(reciprocalParamArr);
}
};
/**
* The arctangent function.
*/
public final Function functionArctan = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(params[0].signum() == -1){
NumberInterface[] negatedParams = {params[0].negate()};
return applyInternal(negatedParams).negate();
}
if(params[0].compareTo(fromInt(params[0].getClass(), 1)) > 0){
NumberInterface[] reciprocalParams = {fromInt(params[0].getClass(), 1).divide(params[0])};
return piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 2))
.subtract(applyInternal(reciprocalParams));
}
if(params[0].compareTo(fromInt(params[0].getClass(), 1)) == 0){
return piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 4));
}
if(params[0].compareTo(new NaiveNumber(0.9).promoteTo(params[0].getClass())) >= 0){
NumberInterface[] newParams = {params[0].multiply(fromInt(params[0].getClass(),2 ))
.divide(fromInt(params[0].getClass(), 1).subtract(params[0].multiply(params[0])))};
return applyInternal(newParams).divide(fromInt(params[0].getClass(), 2));
}
NumberInterface currentPower = params[0], currentTerm = currentPower, sum = currentTerm,
maxError = params[0].getMaxError(), multiplier = currentPower.multiply(currentPower).negate();
int n = 1;
while(FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0){
n += 2;
currentPower = currentPower.multiply(multiplier);
currentTerm = currentPower.divide(fromInt(currentPower.getClass(), n));
sum = sum.add(currentTerm);
}
return sum;
}
};
/**
* The arccotangent function. Range: (0, pi).
*/
public final Function functionArccot = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 2))
.subtract(functionArctan.apply(params));
}
};
public StandardPlugin(PluginManager manager) {
super(manager);
}
@@ -468,16 +609,6 @@ public class StandardPlugin extends Plugin {
return sum;
}
/**
* Returns the maximum error based on the precision of the class of number.
*
* @param number Any instance of the NumberInterface in question (should return an appropriate precision).
* @return the maximum error.
*/
private static NumberInterface getMaxError(NumberInterface number) {
return fromInt(number.getClass(), 10).intPow(-number.getMaxPrecision());
}
/**
* A factorial function that uses memoization for each number class; it efficiently
* computes factorials of non-negative integers.
@@ -509,7 +640,7 @@ public class StandardPlugin extends Plugin {
*/
private static NumberInterface sinTaylor(NumberInterface x) {
NumberInterface power = x, multiplier = x.multiply(x).negate(), currentTerm = x, sum = x;
NumberInterface maxError = getMaxError(x);
NumberInterface maxError = x.getMaxError();
int n = 1;
do {
n += 2;
@@ -575,6 +706,12 @@ public class StandardPlugin extends Plugin {
registerFunction("sec", functionSec);
registerFunction("csc", functionCsc);
registerFunction("cot", functionCot);
registerFunction("arcsin", functionArcsin);
registerFunction("arccos", functionArccos);
registerFunction("arccsc", functionArccsc);
registerFunction("arcsec", functionArcsec);
registerFunction("arctan", functionArctan);
registerFunction("arccot", functionArccot);
}
@Override

View File

@@ -1,108 +0,0 @@
package org.nwapw.abacus.tree;
/**
* A tree node that represents an operation being applied to two operands.
*/
public class BinaryNode extends TreeNode {
/**
* The operation being applied.
*/
private String operation;
/**
* The left node of the operation.
*/
private TreeNode left;
/**
* The right node of the operation.
*/
private TreeNode right;
private BinaryNode() {
}
/**
* Creates a new operation node with the given operation
* and no child nodes.
*
* @param operation the operation.
*/
public BinaryNode(String operation) {
this(operation, null, null);
}
/**
* Creates a new operation node with the given operation
* and child nodes.
*
* @param operation the operation.
* @param left the left node of the expression.
* @param right the right node of the expression.
*/
public BinaryNode(String operation, TreeNode left, TreeNode right) {
this.operation = operation;
this.left = left;
this.right = right;
}
/**
* Gets the operation in this node.
*
* @return the operation in this node.
*/
public String getOperation() {
return operation;
}
/**
* Gets the left sub-expression of this node.
*
* @return the left node.
*/
public TreeNode getLeft() {
return left;
}
/**
* Sets the left sub-expression of this node.
*
* @param left the sub-expression to apply.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Gets the right sub-expression of this node.
*
* @return the right node.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the right sub-expression of this node.
*
* @param right the sub-expression to apply.
*/
public void setRight(TreeNode right) {
this.right = right;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
T leftReduce = left.reduce(reducer);
T rightReduce = right.reduce(reducer);
if (leftReduce == null || rightReduce == null) return null;
return reducer.reduceNode(this, leftReduce, rightReduce);
}
@Override
public String toString() {
String leftString = left != null ? left.toString() : "null";
String rightString = right != null ? right.toString() : "null";
return "(" + leftString + operation + rightString + ")";
}
}

View File

@@ -1,85 +0,0 @@
package org.nwapw.abacus.tree;
import java.util.ArrayList;
import java.util.List;
/**
* A node that represents a function call.
*/
public class FunctionNode extends TreeNode {
/**
* The name of the function being called
*/
private String function;
/**
* The list of arguments to the function.
*/
private List<TreeNode> children;
/**
* Creates a function node with no function.
*/
private FunctionNode() {
}
/**
* Creates a new function node with the given function name.
*
* @param function the function name.
*/
public FunctionNode(String function) {
this.function = function;
children = new ArrayList<>();
}
/**
* Gets the function name for this node.
*
* @return the function name.
*/
public String getFunction() {
return function;
}
/**
* Adds a child to the end of this node's child list.
*
* @param node the child to add.
*/
public void appendChild(TreeNode node) {
children.add(node);
}
/**
* Adds a new child to the beginning of this node's child list.
*
* @param node the node to add.
*/
public void prependChild(TreeNode node) {
children.add(0, node);
}
@Override
public <T> T reduce(Reducer<T> reducer) {
Object[] reducedChildren = new Object[children.size()];
for (int i = 0; i < reducedChildren.length; i++) {
reducedChildren[i] = children.get(i).reduce(reducer);
if (reducedChildren[i] == null) return null;
}
return reducer.reduceNode(this, reducedChildren);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(function);
buffer.append("(");
for (int i = 0; i < children.size(); i++) {
buffer.append(children.get(i));
buffer.append(i == children.size() - 1 ? "" : ", ");
}
buffer.append(")");
return buffer.toString();
}
}

View File

@@ -1,49 +0,0 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.number.NumberInterface;
/**
* A node implementation that represents a single number.
*/
public class NumberNode extends TreeNode {
/**
* The number that is represented by this number node.
*/
private NumberInterface number;
/**
* Creates a number node with no number.
*/
public NumberNode() {
number = null;
}
/**
* Creates a new number node with the given double value.
*
* @param newNumber the number for which to create a number node.
*/
public NumberNode(NumberInterface newNumber) {
this.number = newNumber;
}
/**
* Gets the number value of this node.
*
* @return the number value of this node.
*/
public NumberInterface getNumber() {
return number;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
return reducer.reduceNode(this);
}
@Override
public String toString() {
return number != null ? number.toString() : "null";
}
}

View File

@@ -1,17 +0,0 @@
package org.nwapw.abacus.tree;
/**
* An abstract class that represents an expression tree node.
*/
public abstract class TreeNode {
/**
* The function that reduces a tree to a single vale.
*
* @param reducer the reducer used to reduce the tree.
* @param <T> the type the reducer produces.
* @return the result of the reduction, or null on error.
*/
public abstract <T> T reduce(Reducer<T> reducer);
}

View File

@@ -1,63 +0,0 @@
package org.nwapw.abacus.tree;
public class UnaryNode extends TreeNode {
/**
* The operation this node will apply.
*/
private String operation;
/**
* The tree node to apply the operation to.
*/
private TreeNode applyTo;
/**
* Creates a new node with the given operation and no child.
*
* @param operation the operation for this node.
*/
public UnaryNode(String operation) {
this(operation, null);
}
/**
* Creates a new node with the given operation and child.
*
* @param operation the operation for this node.
* @param applyTo the node to apply the function to.
*/
public UnaryNode(String operation, TreeNode applyTo) {
this.operation = operation;
this.applyTo = applyTo;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
Object reducedChild = applyTo.reduce(reducer);
if (reducedChild == null) return null;
return reducer.reduceNode(this, reducedChild);
}
/**
* Gets the operation of this node.
*
* @return the operation this node performs.
*/
public String getOperation() {
return operation;
}
/**
* Gets the node to which this node's operation applies.
*
* @return the tree node to which the operation will be applied.
*/
public TreeNode getApplyTo() {
return applyTo;
}
@Override
public String toString() {
return "(" + (applyTo == null ? "null" : applyTo.toString()) + ")" + operation;
}
}

View File

@@ -0,0 +1,14 @@
package org.nwapw.abacus.function
/**
* A single operator that can be used by Abacus.
*
* This is a data class that holds the information about a single operator, such as a plus or minus.
*
* @param associativity the associativity of this operator, used for order of operations;.
* @param type the type of this operator, used for parsing (infix / prefix / postfix and binary / unary)
* @param precedence the precedence of this operator, used for order of operations.
* @param function the function this operator applies to its arguments.
*/
data class Operator(val associativity: OperatorAssociativity, val type: OperatorType,
val precedence: Int, val function: Function)

View File

@@ -0,0 +1,32 @@
package org.nwapw.abacus.fx
import javafx.beans.property.SimpleStringProperty
/**
* A model representing an input / output in the calculator.
*
* The HistoryModel class stores a record of a single user-provided input,
* its parsed form as it was interpreted by the calculator, and the output
* that was provided by the calculator. These are represented as properties
* to allow easy access by JavaFX cells.
*
* @param input the user input
* @param parsed the parsed version of the input.
* @param output the output string.
*/
class HistoryModel(input: String, parsed: String, output: String){
/**
* The property that holds the input.
*/
val inputProperty = SimpleStringProperty(input)
/**
* The property that holds the parsed input.
*/
val parsedProperty = SimpleStringProperty(parsed)
/**
* The property that holds the output.
*/
val outputProperty = SimpleStringProperty(output)
}

View File

@@ -0,0 +1,31 @@
package org.nwapw.abacus.fx
import javafx.beans.property.SimpleBooleanProperty
/**
* A model representing a plugin that can be disabled or enabled.
*
* ToggleablePlugin is a model that is used to present to the user the option
* of disabling / enabling plugins. The class name in this plugin is stored if
* its "enabledPropery" is false, essentially blacklisting the plugin.
*
* @param className the name of the class that this model concerns.
* @param enabled whether or not the model should start enabled.
*/
class ToggleablePlugin (val className: String, enabled: Boolean) {
/**
* The property used to interact with JavaFX components.
*/
val enabledProperty = SimpleBooleanProperty(enabled)
/**
* Checks whether this plugin is currently enabled or not.
*
* @return true if it is enabled, false otherwise.
*/
fun isEnabled(): Boolean {
return enabledProperty.value
}
}

View File

@@ -0,0 +1,26 @@
package org.nwapw.abacus.tree
/**
* A tree node that holds a binary operation.
*
* This node represents any binary operation, such as binary infix or binary postfix. The only
* currently implemented into Abacus is binary infix, but that has more to do with the parser than
* this class, which doesn't care about the order that its operation and nodes were found in text.
*
* @param operation the operation this node performs on its children.
* @param left the left node.
* @param right the right node.
*/
data class BinaryNode(val operation: String, val left: TreeNode? = null, val right: TreeNode?) : TreeNode() {
override fun <T : Any> reduce(reducer: Reducer<T>): T? {
val leftReduce = left?.reduce(reducer) ?: return null
val rightReduce = right?.reduce(reducer) ?: return null
return reducer.reduceNode(this, leftReduce, rightReduce)
}
override fun toString(): String {
return "(" + (left?.toString() ?: "null") + operation + (right?.toString() ?: "null") + ")"
}
}

View File

@@ -0,0 +1,52 @@
package org.nwapw.abacus.tree
/**
* A tree node that holds a function call.
*
* The function call node can hold any number of children, and passes the to the appropriate reducer,
* but that is its sole purpose.
*
* @param function the function string.
*/
data class FunctionNode(val function: String) : TreeNode() {
/**
* List of function parameters added to this node.
*/
val children: MutableList<TreeNode> = mutableListOf()
override fun <T : Any> reduce(reducer: Reducer<T>): T? {
val children = Array<Any?>(children.size, { children[it].reduce(reducer) ?: return null; })
return reducer.reduceNode(this, *children)
}
override fun toString(): String {
val buffer = StringBuffer()
buffer.append(function)
buffer.append('(')
for (i in 0 until children.size) {
buffer.append(children[i].toString())
buffer.append(if (i == children.size - 1) ")" else ",")
}
return buffer.toString()
}
/**
* Appends a child to this node's list of children.
*
* @node the node to append.
*/
fun appendChild(node: TreeNode){
children.add(node)
}
/**
* Prepends a child to this node's list of children.
*
* @node the node to prepend.
*/
fun prependChild(node: TreeNode){
children.add(0, node)
}
}

View File

@@ -0,0 +1,23 @@
package org.nwapw.abacus.tree
import org.nwapw.abacus.number.NumberInterface
/**
* A tree node that holds a single number value.
*
* This is a tree node that holds a single NumberInterface, which represents any number,
* and is not defined during compile time.
*
* @number the number value of this node.
*/
data class NumberNode(val number: NumberInterface) : TreeNode() {
override fun <T : Any> reduce(reducer: Reducer<T>): T? {
return reducer.reduceNode(this)
}
override fun toString(): String {
return number.toString()
}
}

View File

@@ -0,0 +1,10 @@
package org.nwapw.abacus.tree
/**
* A tree node.
*/
abstract class TreeNode {
abstract fun <T: Any> reduce(reducer: Reducer<T>) : T?
}

View File

@@ -0,0 +1,23 @@
package org.nwapw.abacus.tree
/**
* A tree node that holds a unary operation.
*
* This node holds a single operator applied to a single parameter, and does not care
* whether the operation was found before or after the parameter in the text.
*
* @param operation the operation applied to the given node.
* @param applyTo the node to which the operation will be applied.
*/
data class UnaryNode(val operation: String, val applyTo: TreeNode? = null) : TreeNode() {
override fun <T : Any> reduce(reducer: Reducer<T>): T? {
val reducedChild = applyTo?.reduce(reducer) ?: return null
return reducer.reduceNode(this, reducedChild)
}
override fun toString(): String {
return "(" + (applyTo?.toString() ?: "null") + ")" + operation
}
}

View File

@@ -88,8 +88,8 @@ public class CalculationTests {
public void testExp(){
testOutput("exp0", "exp(0)", "1");
testOutput("exp1", "exp(1)", "2.718281828459045235360287471352662497757247");
testOutput("exp300", "exp(300)", "19424263952412559365842088360176992193662086");
testOutput("exp300", "exp(300)", "19424263952412559365842088360176992193662086");
testOutput("exp300", "exp(300)", "1.9424263952412559365842088360176992193662086");
testOutput("exp(-500)", "exp((500)`)", "7.1245764067412855315491573771227552469277568");
}
@Test
@@ -99,6 +99,9 @@ public class CalculationTests {
testOutput("2^1", "(2^1)", "2");
testOutput("2^-1", "(2^(1)`)", "0.5");
testOutput("2^50", "(2^50)", "112589990684262");
testOutput("7^(-sqrt2*17)", "(7^((sqrt(2)*17))`)", "4.81354609155297814551845300063563");
testEvalError("0^0", "(0^0)");
testEvalError("(-13)^.9999", "((13)`^0.9999)");
}
}