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

Compare commits

..

3 Commits

Author SHA1 Message Date
rileyJones
051be8d49e add stop on node 2017-08-02 11:04:35 -07:00
rileyJones
f464bcff6f Add stop function by ignoring result of calculations 2017-08-01 12:06:58 -07:00
rileyJones
dd915136c6 Add Stop Button 2017-07-31 14:55:20 -07:00
16 changed files with 287 additions and 567 deletions

View File

@@ -1,12 +1,12 @@
package org.nwapw.abacus;
import org.nwapw.abacus.config.ConfigurationObject;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.parsing.LexerTokenizer;
import org.nwapw.abacus.parsing.ShuntingYardParser;
import org.nwapw.abacus.parsing.TreeBuilder;
import org.nwapw.abacus.plugin.ClassFinder;
import org.nwapw.abacus.plugin.NumberImplementation;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.plugin.StandardPlugin;
import org.nwapw.abacus.tree.NumberReducer;
@@ -16,6 +16,7 @@ import org.nwapw.abacus.window.Window;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
/**
* The main calculator class. This is responsible
@@ -24,7 +25,10 @@ import java.io.IOException;
*/
public class Abacus {
public static final NumberImplementation DEFAULT_IMPLEMENTATION = StandardPlugin.IMPLEMENTATION_NAIVE;
/**
* The default implementation to use for the number representation.
*/
public static final Class<? extends NumberInterface> DEFAULT_NUMBER = NaiveNumber.class;
/**
* The file used for saving and loading configuration.
*/
@@ -49,7 +53,10 @@ public class Abacus {
* from a string.
*/
private TreeBuilder treeBuilder;
private Window window;
public boolean getStop(){
return window.getStop();
}
/**
* Creates a new instance of the Abacus calculator.
*/
@@ -129,7 +136,7 @@ public class Abacus {
* @return the resulting tree, null if the tree builder or the produced tree are null.
*/
public TreeNode parseString(String input) {
return treeBuilder.fromString(input);
return treeBuilder.fromString(input,this);
}
/**
@@ -150,10 +157,19 @@ public class Abacus {
* @return the resulting number.
*/
public NumberInterface numberFromString(String numberString) {
NumberImplementation toInstantiate =
pluginManager.numberImplementationFor(configuration.getNumberImplementation());
if (toInstantiate == null) toInstantiate = DEFAULT_IMPLEMENTATION;
Class<? extends NumberInterface> toInstantiate =
pluginManager.numberFor(configuration.getNumberImplementation());
if (toInstantiate == null) toInstantiate = DEFAULT_NUMBER;
return toInstantiate.instanceForString(numberString);
try {
return toInstantiate.getConstructor(String.class).newInstance(numberString);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public void setWindow(Window window) {
this.window = window;
}
}

View File

@@ -1,6 +1,10 @@
package org.nwapw.abacus.function;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.PreciseNumber;
import java.util.HashMap;
/**
* A function that operates on one or more
@@ -8,6 +12,15 @@ import org.nwapw.abacus.number.NumberInterface;
*/
public abstract class Function {
/**
* A map to correctly promote different number implementations to each other.
*/
private static final HashMap<Class<? extends NumberInterface>, Integer> priorityMap =
new HashMap<Class<? extends NumberInterface>, Integer>() {{
put(NaiveNumber.class, 0);
put(PreciseNumber.class, 1);
}};
/**
* Checks whether the given params will work for the given function.
*

View File

@@ -93,26 +93,6 @@ public class NaiveNumber implements NumberInterface {
return this.compareTo(ZERO);
}
@Override
public NumberInterface ceiling() {
return new NaiveNumber(Math.ceil(value));
}
@Override
public NumberInterface floor() {
return new NaiveNumber(Math.floor(value));
}
@Override
public NumberInterface fractionalPart() {
return new NaiveNumber(value - Math.floor(value));
}
@Override
public int intValue() {
return (int)value;
}
@Override
public NumberInterface promoteTo(Class<? extends NumberInterface> toClass) {
if (toClass == this.getClass()) return this;

View File

@@ -79,31 +79,6 @@ public interface NumberInterface {
*/
int signum();
/**
* Returns the least integer greater than or equal to the number.
* @return the least integer >= the number, if int can hold the value.
*/
NumberInterface ceiling();
/**
* Return the greatest integer less than or equal to the number.
* @return the greatest int >= the number, if int can hold the value.
*/
NumberInterface floor();
/**
* Returns the fractional part of the number.
* @return the fractional part of the number.
*/
NumberInterface fractionalPart();
/**
* Returns the integer representation of this number, discarding any fractional part,
* if int can hold the value.
* @return
*/
int intValue();
/**
* Promotes this class to another number class.
*

View File

@@ -8,15 +8,15 @@ public class PreciseNumber implements NumberInterface {
/**
* The number one.
*/
public static final PreciseNumber ONE = new PreciseNumber(BigDecimal.ONE);
static final PreciseNumber ONE = new PreciseNumber(BigDecimal.ONE);
/**
* The number zero.
*/
public static final PreciseNumber ZERO = new PreciseNumber(BigDecimal.ZERO);
static final PreciseNumber ZERO = new PreciseNumber(BigDecimal.ZERO);
/**
* The number ten.
*/
public static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
/**
* The value of the PreciseNumber.
@@ -44,12 +44,12 @@ public class PreciseNumber implements NumberInterface {
@Override
public int getMaxPrecision() {
return 65;
return 54;
}
@Override
public NumberInterface multiply(NumberInterface multiplier) {
return new PreciseNumber(this.value.multiply(((PreciseNumber) multiplier).value));
return new PreciseNumber(value.multiply(((PreciseNumber) multiplier).value));
}
@Override
@@ -94,41 +94,6 @@ public class PreciseNumber implements NumberInterface {
return value.signum();
}
@Override
public NumberInterface ceiling() {
String str = value.toPlainString();
int decimalIndex = str.indexOf('.');
if(decimalIndex != -1){
return this.floor().add(ONE);
}
return this;
}
@Override
public NumberInterface floor() {
String str = value.toPlainString();
int decimalIndex = str.indexOf('.');
if(decimalIndex != -1){
return new PreciseNumber(str.substring(0, decimalIndex));
}
return this;
}
@Override
public NumberInterface fractionalPart() {
String str = value.toPlainString();
int decimalIndex = str.indexOf('.');
if(decimalIndex != -1){
return new PreciseNumber(str.substring(decimalIndex + 1));
}
return ZERO;
}
@Override
public int intValue() {
return value.intValue();
}
@Override
public NumberInterface negate() {
return new PreciseNumber(value.negate());
@@ -144,7 +109,7 @@ public class PreciseNumber implements NumberInterface {
@Override
public String toString() {
BigDecimal rounded = value.setScale(getMaxPrecision() - 15, RoundingMode.HALF_UP);
BigDecimal rounded = value.setScale(getMaxPrecision() - 4, RoundingMode.HALF_UP);
return rounded.stripTrailingZeros().toPlainString();
}
}

View File

@@ -1,5 +1,6 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.tree.TreeNode;
import java.util.List;
@@ -18,5 +19,5 @@ public interface Parser<T> {
* @param tokens the tokens to construct a tree from.
* @return the constructed tree, or null on error.
*/
public TreeNode constructTree(List<T> tokens);
public TreeNode constructTree(List<T> tokens,Abacus trace);
}

View File

@@ -34,6 +34,8 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
*/
private Map<String, OperatorType> typeMap;
//private Abacus trace;
/**
* Creates a new Shunting Yard parser with the given Abacus instance.
*
@@ -116,7 +118,8 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
* @param matches the list of tokens from the source string.
* @return the construct tree expression.
*/
public TreeNode constructRecursive(List<Match<TokenType>> matches) {
public TreeNode constructRecursive(List<Match<TokenType>> matches,Abacus trace) {
//this.trace = trace;
if (matches.size() == 0) return null;
Match<TokenType> match = matches.remove(0);
TokenType matchType = match.getType();
@@ -124,22 +127,22 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
String operator = match.getContent();
OperatorType type = typeMap.get(operator);
if (type == OperatorType.BINARY_INFIX) {
TreeNode right = constructRecursive(matches);
TreeNode left = constructRecursive(matches);
TreeNode right = constructRecursive(matches,trace);
TreeNode left = constructRecursive(matches,trace);
if (left == null || right == null) return null;
else return new BinaryInfixNode(operator, left, right);
else return new BinaryInfixNode(operator, left, right,trace);
} else {
TreeNode applyTo = constructRecursive(matches);
TreeNode applyTo = constructRecursive(matches,trace);
if (applyTo == null) return null;
else return new UnaryPrefixNode(operator, applyTo);
else return new UnaryPrefixNode(operator, applyTo,trace);
}
} else if (matchType == TokenType.NUM) {
return new NumberNode(abacus.numberFromString(match.getContent()));
} else if (matchType == TokenType.FUNCTION) {
String functionName = match.getContent();
FunctionNode node = new FunctionNode(functionName);
FunctionNode node = new FunctionNode(functionName,trace);
while (!matches.isEmpty() && matches.get(0).getType() != TokenType.INTERNAL_FUNCTION_END) {
TreeNode argument = constructRecursive(matches);
TreeNode argument = constructRecursive(matches,trace);
if (argument == null) return null;
node.prependChild(argument);
}
@@ -151,10 +154,10 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
}
@Override
public TreeNode constructTree(List<Match<TokenType>> tokens) {
public TreeNode constructTree(List<Match<TokenType>> tokens,Abacus trace) {
tokens = intoPostfix(new ArrayList<>(tokens));
Collections.reverse(tokens);
return constructRecursive(tokens);
return constructRecursive(tokens,trace);
}
@Override

View File

@@ -1,5 +1,6 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.tree.TreeNode;
import java.util.List;
@@ -41,10 +42,10 @@ public class TreeBuilder<T> {
* @param input the string to parse into a tree.
* @return the resulting tree.
*/
public TreeNode fromString(String input) {
public TreeNode fromString(String input,Abacus trace) {
List<T> tokens = tokenizer.tokenizeString(input);
if (tokens == null) return null;
return parser.constructTree(tokens);
return parser.constructTree(tokens,trace);
}
}

View File

@@ -1,75 +0,0 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.number.NumberInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* A class that holds data about a number implementation.
*/
public abstract class NumberImplementation {
/**
* The list of paths through which this implementation can be promoted.
*/
protected Map<Class<? extends NumberInterface>, Function<NumberInterface, NumberInterface>> promotionPaths;
/**
* The implementation class for this implementation.
*/
private Class<? extends NumberInterface> implementation;
/**
* The priority of converting into this number implementation.
*/
private int priority;
/**
* Creates a new number implementation with the given data.
* @param implementation the implementation class.
* @param priority the priority, higher -> more likely to be converted into.
*/
public NumberImplementation(Class<? extends NumberInterface> implementation, int priority){
this.implementation = implementation;
this.priority = priority;
promotionPaths = new HashMap<>();
}
/**
* Gets the list of all promotion paths this implementation can take.
* @return the map of documentation paths.
*/
public final Map<Class<? extends NumberInterface>, Function<NumberInterface, NumberInterface>> getPromotionPaths(){
return promotionPaths;
}
/**
* Gets the implementation class used by this implementation.
* @return the implementation class.
*/
public final Class<? extends NumberInterface> getImplementation(){
return implementation;
}
/**
* Gets the priority of this number implementation.
* @return the priority.
*/
public final int getPriority(){
return priority;
}
/**
* Abstract function to create a new instance from a string.
* @param string the string to create a number from.
* @return the resulting number.
*/
public abstract NumberInterface instanceForString(String string);
/**
* Get the instance of pi with the given implementation.
* @return pi
*/
public abstract NumberInterface instanceForPi();
}

View File

@@ -26,9 +26,9 @@ public abstract class Plugin {
*/
private Map<String, Operator> operators;
/**
* The map of the number implementations this plugin provides.
* A hash map of operators mapped to their string names.
*/
private Map<String, NumberImplementation> numberImplementations;
private Map<String, Class<? extends NumberInterface>> numbers;
/**
* The plugin manager in which to search for functions
* not inside this package,
@@ -51,7 +51,7 @@ public abstract class Plugin {
this.manager = manager;
functions = new HashMap<>();
operators = new HashMap<>();
numberImplementations = new HashMap<>();
numbers = new HashMap<>();
enabled = false;
}
@@ -74,12 +74,12 @@ public abstract class Plugin {
}
/**
* Gets the list of number implementations provided by this plugin.
* Gets the list of all numbers provided by this plugin.
*
* @return the list of registered number implementations.
* @return the list of registered numbers.
*/
public final Set<String> providedNumberImplementations(){
return numberImplementations.keySet();
public final Set<String> providedNumbers() {
return numbers.keySet();
}
/**
@@ -103,13 +103,13 @@ public abstract class Plugin {
}
/**
* Gets the number implementation under the given name.
* Gets the class under the given name.
*
* @param name the name of the number implementation to look up.
* @return the number implementation associated with that name, or null if the plugin doesn't provide it.
* @param numberName the name of the class.
* @return the class, or null if the plugin doesn't provide it.
*/
public final NumberImplementation getNumberImplementation(String name){
return numberImplementations.get(name);
public final Class<? extends NumberInterface> getNumber(String numberName) {
return numbers.get(numberName);
}
/**
@@ -158,13 +158,16 @@ public abstract class Plugin {
}
/**
* To be used in load(). Registers a new number implementation with the plugin.
* This makes it accessible to the plugin manager.
* @param name the name of the implementation.
* @param implementation the actual implementation class to register.
* To be used in load(). Registers a number class
* with the plugin internally, which makes it possible
* for the user to select it as an "implementation" for the
* number that they would like to use.
*
* @param name the name to register it under.
* @param toRegister the class to register.
*/
protected final void registerNumberImplementation(String name, NumberImplementation implementation){
numberImplementations.put(name, implementation);
protected final void registerNumber(String name, Class<? extends NumberInterface> toRegister) {
numbers.put(name, toRegister);
}
/**
@@ -191,30 +194,6 @@ public abstract class Plugin {
return manager.operatorFor(name);
}
/**
* Searches the PluginManager for the given number implementation
* name. This can be used by the plugins internally in order to find
* implementations that they do not provide.
*
* @param name the name for which to search.
* @return the resulting number implementation, or null if none was found.
*/
protected final NumberImplementation numberImplementationFor(String name){
return manager.numberImplementationFor(name);
}
/**
* Searches the plugin manager for a Pi value for the given number implementation.
* This is done so that number implementations with various degrees of precision
* can provide their own pi values, without losing said precision by
* promoting NaiveNumbers.
* @param forClass the class to which to find the pi instance.
* @return the pi value for the given class.
*/
protected final NumberInterface getPi(Class<? extends NumberInterface> forClass){
return manager.piFor(forClass);
}
/**
* Abstract method to be overridden by plugin implementation, in which the plugins
* are supposed to register the functions they provide and do any other

View File

@@ -32,19 +32,10 @@ public class PluginManager {
*/
private Map<String, Operator> cachedOperators;
/**
* The list of number implementations that have
* List of registered number implementations that have
* been cached, that is, found in a plugin and returned.
*/
private Map<String, NumberImplementation> cachedNumberImplementations;
/**
* The list of number implementations that have been
* found by their implementation class.
*/
private Map<Class<? extends NumberInterface>, NumberImplementation> cachedInterfaceImplementations;
/**
* The pi values for each implementation class that have already been computer.
*/
private Map<Class<? extends NumberInterface>, NumberInterface> cachedPi;
private Map<String, Class<? extends NumberInterface>> cachedNumbers;
/**
* List of all functions loaded by the plugins.
*/
@@ -54,9 +45,9 @@ public class PluginManager {
*/
private Set<String> allOperators;
/**
* List of all the number implementations loaded by the plugins.
* List of all numbers loaded by the plugins.
*/
private Set<String> allNumberImplementations;
private Set<String> allNumbers;
/**
* The list of plugin listeners attached to this instance.
*/
@@ -70,12 +61,10 @@ public class PluginManager {
plugins = new HashSet<>();
cachedFunctions = new HashMap<>();
cachedOperators = new HashMap<>();
cachedNumberImplementations = new HashMap<>();
cachedInterfaceImplementations = new HashMap<>();
cachedPi = new HashMap<>();
cachedNumbers = new HashMap<>();
allFunctions = new HashSet<>();
allOperators = new HashSet<>();
allNumberImplementations = new HashSet<>();
allNumbers = new HashSet<>();
listeners = new HashSet<>();
}
@@ -91,13 +80,12 @@ public class PluginManager {
* @param getFunction the function to get the T value under the given name
* @param name the name to search for
* @param <T> the type of element being search
* @param <K> the type of key that the cache is indexed by.
* @return the retrieved element, or null if it was not found.
*/
private static <T, K> T searchCached(Collection<Plugin> plugins, Map<K, T> cache,
java.util.function.Function<Plugin, Set<K>> setFunction,
java.util.function.BiFunction<Plugin, K, T> getFunction,
K name) {
private static <T> T searchCached(Collection<Plugin> plugins, Map<String, T> cache,
java.util.function.Function<Plugin, Set<String>> setFunction,
java.util.function.BiFunction<Plugin, String, T> getFunction,
String name) {
if (cache.containsKey(name)) return cache.get(name);
T loadedValue = null;
@@ -133,51 +121,13 @@ public class PluginManager {
}
/**
* Gets the number implementation under the given name.
* Gets a numer implementation under the given name.
*
* @param name the name of the implementation.
* @return the implementation.
* @return the implementation class
*/
public NumberImplementation numberImplementationFor(String name){
return searchCached(plugins, cachedNumberImplementations, Plugin::providedNumberImplementations,
Plugin::getNumberImplementation, name);
}
/**
* Gets the number implementation for the given implementation class.
* @param name the class for which to find the implementation.
* @return the implementation.
*/
public NumberImplementation interfaceImplementationFor(Class<? extends NumberInterface> name){
if(cachedInterfaceImplementations.containsKey(name)) return cachedInterfaceImplementations.get(name);
NumberImplementation toReturn = null;
outside:
for(Plugin plugin : plugins){
for(String implementationName : plugin.providedNumberImplementations()){
NumberImplementation implementation = plugin.getNumberImplementation(implementationName);
if(implementation.getImplementation().equals(name)) {
toReturn = implementation;
break outside;
}
}
}
cachedInterfaceImplementations.put(name, toReturn);
return toReturn;
}
/**
* Gets the mathematical constant pi for the given implementation class.
* @param forClass the class for which to find pi.
* @return pi
*/
public NumberInterface piFor(Class<? extends NumberInterface> forClass){
if(cachedPi.containsKey(forClass)) return cachedPi.get(forClass);
NumberImplementation implementation = interfaceImplementationFor(forClass);
NumberInterface generatedPi = null;
if(implementation != null){
generatedPi = implementation.instanceForPi();
}
cachedPi.put(forClass, generatedPi);
return generatedPi;
public Class<? extends NumberInterface> numberFor(String name) {
return searchCached(plugins, cachedNumbers, Plugin::providedNumbers, Plugin::getNumber, name);
}
/**
@@ -214,7 +164,7 @@ public class PluginManager {
for (Plugin plugin : plugins) {
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumberImplementations.addAll(plugin.providedNumberImplementations());
allNumbers.addAll(plugin.providedNumbers());
}
listeners.forEach(e -> e.onLoad(this));
}
@@ -226,7 +176,7 @@ public class PluginManager {
for (Plugin plugin : plugins) plugin.disable();
allFunctions.clear();
allOperators.clear();
allNumberImplementations.clear();
allNumbers.clear();
listeners.forEach(e -> e.onUnload(this));
}
@@ -257,12 +207,12 @@ public class PluginManager {
}
/**
* Gets all the number implementations loaded by the Plugin Manager.
* Gets all the number implementations loaded by the Plugin Manager
*
* @return the set of all implementations that were loaded.
* @return the set of all implementations that were loaded
*/
public Set<String> getAllNumberImplementations(){
return allNumberImplementations;
public Set<String> getAllNumbers() {
return allNumbers;
}
/**

View File

@@ -8,8 +8,6 @@ import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.PreciseNumber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.BiFunction;
/**
@@ -18,8 +16,6 @@ import java.util.function.BiFunction;
*/
public class StandardPlugin extends Plugin {
private static HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>> factorialLists = new HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>>();
/**
* The addition operator, +
*/
@@ -95,9 +91,7 @@ public class StandardPlugin extends Plugin {
//private HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>> storedList = new HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>>();
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1
&& params[0].fractionalPart().compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0
&& params[0].signum() >= 0;
return params.length == 1;
}
@Override
@@ -158,40 +152,17 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface maxError = getMaxError(params[0]);
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);
boolean takeReciprocal = params[0].signum() == -1;
params[0] = FUNCTION_ABS.apply(params[0]);
NumberInterface sum = sumSeries(params[0], StandardPlugin::getExpSeriesTerm, getNTermsExp(getMaxError(params[0]), params[0]));
if (takeReciprocal) {
sum = NaiveNumber.ONE.promoteTo(sum.getClass()).divide(sum);
}
return sum;
}
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.
NumberInterface sum = NaiveNumber.ONE.promoteTo(params[0].getClass());
NumberInterface nextNumerator = params[0];
NumberInterface left = params[0].multiply((new NaiveNumber(3)).promoteTo(params[0].getClass()).intPow(params[0].ceiling().intValue())), right = maxError;
do{
sum = sum.add(nextNumerator.divide(factorial(params[0].getClass(), n+1)));
n++;
nextNumerator = nextNumerator.multiply(params[0]);
left = left.multiply(params[0]);
NumberInterface nextN = (new NaiveNumber(n+1)).promoteTo(params[0].getClass());
right = right.multiply(nextN);
//System.out.println(left + ", " + right);
}
while(left.compareTo(right) > 0);
//System.out.println(n+1);
return sum;
}
}
};
/**
* The natural log function.
* The natural log function, ln(exp(1)) = 1
*/
public static final Function FUNCTION_LN = new Function() {
@Override
@@ -268,7 +239,7 @@ public class StandardPlugin extends Plugin {
}
};
/**
* The square root function.
* The square root function, sqrt(4) = 2
*/
public static final Function FUNCTION_SQRT = new Function() {
@Override
@@ -282,149 +253,43 @@ public class StandardPlugin extends Plugin {
}
};
/**
* The sine function (the argument is interpreted in radians).
*/
public final Function functionSin = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface pi = getPi(params[0].getClass());
NumberInterface twoPi = pi.multiply(new NaiveNumber(2).promoteTo(pi.getClass()));
NumberInterface theta = getSmallAngle(params[0], pi);
//System.out.println(theta);
if(theta.compareTo(pi.multiply(new NaiveNumber(1.5).promoteTo(twoPi.getClass()))) >= 0){
theta = theta.subtract(twoPi);
}
else if(theta.compareTo(pi.divide(new NaiveNumber(2).promoteTo(pi.getClass()))) > 0){
theta = pi.subtract(theta);
}
//System.out.println(theta);
return sinTaylor(theta);
}
};
public final Function functionCos = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return functionSin.apply(getPi(params[0].getClass()).divide(new NaiveNumber(2).promoteTo(params[0].getClass()))
.subtract(params[0]));
}
};
public final Function functionTan = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return functionSin.apply(params[0]).divide(functionCos.apply(params[0]));
}
};
public final Function functionSec = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionCos.apply(params[0]));
}
};
public final Function functionCsc = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionSin.apply(params[0]));
}
};
public final Function functionCot = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return functionCos.apply(params[0]).divide(functionCos.apply(params[0]));
}
};
/**
* The implementation for double-based naive numbers.
*/
public static final NumberImplementation IMPLEMENTATION_NAIVE = new NumberImplementation(NaiveNumber.class, 0) {
@Override
public NumberInterface instanceForString(String string) {
return new NaiveNumber(string);
}
@Override
public NumberInterface instanceForPi() {
return new NaiveNumber(Math.PI);
}
};
/**
* The implementation for the infinite-precision BigDecimal.
*/
public static final NumberImplementation IMPLEMENTATION_PRECISE = new NumberImplementation(PreciseNumber.class, 0) {
@Override
public NumberInterface instanceForString(String string) {
return new PreciseNumber(string);
}
@Override
public NumberInterface instanceForPi() {
NumberInterface C = FUNCTION_SQRT.apply(new PreciseNumber("10005")).multiply(new PreciseNumber("426880"));
NumberInterface M = PreciseNumber.ONE;
NumberInterface L = new PreciseNumber("13591409");
NumberInterface X = M;
NumberInterface sum = L;
int termsNeeded = C.getMaxPrecision()/13 + 1;
NumberInterface lSummand = new PreciseNumber("545140134");
NumberInterface xMultiplier = new PreciseNumber("262537412")
.multiply(new PreciseNumber("1000000000"))
.add(new PreciseNumber("640768000"))
.negate();
for(int i = 0; i < termsNeeded; i++){
M = M
.multiply(new NaiveNumber(12*i+2).promoteTo(PreciseNumber.class))
.multiply(new NaiveNumber(12*i+6).promoteTo(PreciseNumber.class))
.multiply(new NaiveNumber(12*i+10).promoteTo(PreciseNumber.class))
.divide(new NaiveNumber(Math.pow(i+1,3)).promoteTo(PreciseNumber.class));
L = L.add(lSummand);
X = X.multiply(xMultiplier);
sum = sum.add(M.multiply(L).divide(X));
}
return C.divide(sum);
}
};
public StandardPlugin(PluginManager manager) {
super(manager);
}
/**
* Returns the nth term of the Taylor series (centered at 0) of e^x
*
* @param n the term required (n >= 0).
* @param x the real number at which the series is evaluated.
* @return the nth term of the series.
*/
private static NumberInterface getExpSeriesTerm(int n, NumberInterface x) {
return x.intPow(n).divide(OP_FACTORIAL.getFunction().apply((new NaiveNumber(n)).promoteTo(x.getClass())));
}
/**
* Returns the number of terms needed to evaluate the exponential function (at x)
* such that the error is at most maxError.
*
* @param maxError Maximum error permissible (This should probably be positive.)
* @param x where the function is evaluated.
* @return the number of terms needed to evaluate the exponential function.
*/
private static int getNTermsExp(NumberInterface maxError, NumberInterface x) {
//We need n such that |x^(n+1)| <= (n+1)! * maxError
//The variables LHS and RHS refer to the above inequality.
int n = 0;
x = FUNCTION_ABS.apply(x);
NumberInterface LHS = x, RHS = maxError;
while (LHS.compareTo(RHS) > 0) {
n++;
LHS = LHS.multiply(x);
RHS = RHS.multiply(new NaiveNumber(n + 1).promoteTo(RHS.getClass()));
}
return n;
}
/**
* Returns a partial sum of a series whose terms are given by the nthTermFunction, evaluated at x.
*
@@ -453,8 +318,8 @@ public class StandardPlugin extends Plugin {
@Override
public void onEnable() {
registerNumberImplementation("naive", IMPLEMENTATION_NAIVE);
registerNumberImplementation("precise", IMPLEMENTATION_PRECISE);
registerNumber("naive", NaiveNumber.class);
registerNumber("precise", PreciseNumber.class);
registerOperator("+", OP_ADD);
registerOperator("-", OP_SUBTRACT);
@@ -467,12 +332,6 @@ public class StandardPlugin extends Plugin {
registerFunction("exp", FUNCTION_EXP);
registerFunction("ln", FUNCTION_LN);
registerFunction("sqrt", FUNCTION_SQRT);
registerFunction("sin", functionSin);
registerFunction("cos", functionCos);
registerFunction("tan", functionTan);
registerFunction("sec", functionSec);
registerFunction("csc", functionCsc);
registerFunction("cot", functionCot);
}
@Override
@@ -480,58 +339,4 @@ public class StandardPlugin extends Plugin {
}
/**
* A factorial function that uses memoization for each number class; it efficiently
* computes factorials of non-negative integers.
* @param numberClass type of number to return.
* @param n non-negative integer.
* @return a number of numClass with value n factorial.
*/
public static NumberInterface factorial(Class<? extends NumberInterface> numberClass, int n){
if(!factorialLists.containsKey(numberClass)){
factorialLists.put(numberClass, new ArrayList<NumberInterface>());
factorialLists.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
factorialLists.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
}
ArrayList<NumberInterface> list = factorialLists.get(numberClass);
if(n >= list.size()){
while(list.size() < n + 16){
list.add(list.get(list.size()-1).multiply(new NaiveNumber(list.size()).promoteTo(numberClass)));
}
}
return list.get(n);
}
/**
* Returns the value of the Taylor series for sin (centered at 0) at x.
* @param x where the series is evaluated.
* @return the value of the series
*/
private static NumberInterface sinTaylor(NumberInterface x){
NumberInterface power = x, multiplier = x.multiply(x).negate(), currentTerm = x, sum = x;
NumberInterface maxError = getMaxError(x);
int n = 1;
do{
n += 2;
power = power.multiply(multiplier);
currentTerm = power.divide(factorial(x.getClass(), n));
sum = sum.add(currentTerm);
} while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0);
return sum;
}
/**
* Returns an equivalent angle in the interval [0, 2pi)
* @param phi an angle (in radians).
* @return theta in [0, 2pi) that differs from phi by a multiple of 2pi.
*/
private static NumberInterface getSmallAngle(NumberInterface phi, NumberInterface pi){
NumberInterface twoPi = pi.multiply(new NaiveNumber("2").promoteTo(phi.getClass()));
NumberInterface theta = FUNCTION_ABS.apply(phi).subtract(twoPi
.multiply(FUNCTION_ABS.apply(phi).divide(twoPi).floor())); //Now theta is in [0, 2pi).
if(phi.signum() < 0){
theta = twoPi.subtract(theta);
}
return theta;
}
}

View File

@@ -1,5 +1,7 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus;
/**
* A tree node that represents an operation being applied to two operands.
*/
@@ -17,6 +19,7 @@ public class BinaryInfixNode extends TreeNode {
* The right node of the operation.
*/
private TreeNode right;
private Abacus trace;
private BinaryInfixNode() {
}
@@ -27,8 +30,8 @@ public class BinaryInfixNode extends TreeNode {
*
* @param operation the operation.
*/
public BinaryInfixNode(String operation) {
this(operation, null, null);
public BinaryInfixNode(String operation,Abacus trace) {
this(operation, null, null,trace);
}
/**
@@ -39,10 +42,11 @@ public class BinaryInfixNode extends TreeNode {
* @param left the left node of the expression.
* @param right the right node of the expression.
*/
public BinaryInfixNode(String operation, TreeNode left, TreeNode right) {
public BinaryInfixNode(String operation, TreeNode left, TreeNode right,Abacus trace) {
this.operation = operation;
this.left = left;
this.right = right;
this.trace = trace;
}
/**
@@ -92,11 +96,16 @@ public class BinaryInfixNode extends TreeNode {
@Override
public <T> T reduce(Reducer<T> reducer) {
if(!trace.getStop()) {
T leftReduce = left.reduce(reducer);
T rightReduce = right.reduce(reducer);
if (leftReduce == null || rightReduce == null) return null;
return reducer.reduceNode(this, leftReduce, rightReduce);
}
return null;
}
@Override
public String toString() {

View File

@@ -1,5 +1,7 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus;
import java.util.ArrayList;
import java.util.List;
@@ -16,6 +18,7 @@ public class FunctionNode extends TreeNode {
* The list of arguments to the function.
*/
private List<TreeNode> children;
private Abacus trace;
/**
* Creates a function node with no function.
@@ -28,9 +31,10 @@ public class FunctionNode extends TreeNode {
*
* @param function the function name.
*/
public FunctionNode(String function) {
public FunctionNode(String function,Abacus trace) {
this.function = function;
children = new ArrayList<>();
this.trace = trace;
}
/**

View File

@@ -1,5 +1,7 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus;
public class UnaryPrefixNode extends TreeNode {
/**
@@ -10,14 +12,15 @@ public class UnaryPrefixNode extends TreeNode {
* The tree node to apply the operation to.
*/
private TreeNode applyTo;
private Abacus trace;
/**
* Creates a new node with the given operation and no child.
*
* @param operation the operation for this node.
*/
public UnaryPrefixNode(String operation) {
this(operation, null);
public UnaryPrefixNode(String operation,Abacus trace) {
this(operation, null,trace);
}
/**
@@ -26,17 +29,21 @@ public class UnaryPrefixNode extends TreeNode {
* @param operation the operation for this node.
* @param applyTo the node to apply the function to.
*/
public UnaryPrefixNode(String operation, TreeNode applyTo) {
public UnaryPrefixNode(String operation, TreeNode applyTo,Abacus trace) {
this.operation = operation;
this.applyTo = applyTo;
this.trace = trace;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
if(!trace.getStop()) {
Object reducedChild = applyTo.reduce(reducer);
if (reducedChild == null) return null;
return reducer.reduceNode(this, reducedChild);
}
return null;
}
/**
* Gets the operation of this node.

View File

@@ -16,12 +16,13 @@ import java.awt.event.MouseEvent;
*/
public class Window extends JFrame {
private static final String CALC_STRING = "Calculate";
private static final String SYNTAX_ERR_STRING = "Syntax Error";
private static final String EVAL_ERR_STRING = "Evaluation Error";
private static final String NUMBER_SYSTEM_LABEL = "Number Type:";
private static final String FUNCTION_LABEL = "Functions:";
private static final String STOP_STRING = "Stop";
/**
* Array of Strings to which the "calculate" button's text
* changes. For instance, in the graph tab, the name will
@@ -90,7 +91,10 @@ public class Window extends JFrame {
* The "submit" button.
*/
private JButton inputEnterButton;
/**
* The stop calculations button.
*/
private JButton inputStopButton;
/**
* The side panel for separate configuration.
*/
@@ -113,26 +117,80 @@ public class Window extends JFrame {
* The list of functions available to the user.
*/
private JComboBox<String> functionList;
/**
* Thread used for calculations
*/
private Thread calculateThread;
/**
* Check if currently calculating.
*/
private boolean calculating;
/**
* Checks if thread should stop calculating.
*/
private boolean stopCalculating;
/**
* Test variable to check number of threads running in the calculator.
*/
private int count;
/**
* ActionListener that stops calculations.
*/
private ActionListener stopListener = (event) -> {
//System.out.println(count++); //Shows about how many calculation threads are running with the calculating=false command
//calculating = false; //Ignores result of calculation and allows for the start of a new calculation
stopCalculating = true; //Stops calculation at the next node check
//calculateThread.stop(); //Stops thread no matter what, Unsafe
};
/**
* Action listener that causes the input to be evaluated.
* Node check to get whether nodes should continue calculating.
* @return boolean stop calculations if true.
*/
public boolean getStop(){
return stopCalculating;
}
/**
* ActionListener that runs all calculations.
*/
private ActionListener evaluateListener = (event) -> {
TreeNode parsedExpression = abacus.parseString(inputField.getText());
Runnable calculate = new Runnable() {
public void run() {
boolean skip = false;
calculating = true;
TreeNode parsedExpression = null;
parsedExpression = abacus.parseString(inputField.getText());
if (parsedExpression == null) {
lastOutputArea.setText(SYNTAX_ERR_STRING);
return;
skip = true;
}
if(!skip){
NumberInterface numberInterface = abacus.evaluateTree(parsedExpression);
if (numberInterface == null) {
lastOutputArea.setText(EVAL_ERR_STRING);
calculating = false;
stopCalculating = false;
return;
}
if(calculateThread.equals(Thread.currentThread())) {
lastOutput = numberInterface.toString();
historyModel.addEntry(new HistoryTableModel.HistoryEntry(inputField.getText(), parsedExpression, lastOutput));
historyTable.invalidate();
lastOutputArea.setText(lastOutput);
inputField.setText("");
calculating = false;
stopCalculating = false;
}
}
}
};
if(!calculating) {
calculateThread = new Thread(calculate);
calculateThread.setName("a-"+System.currentTimeMillis());
calculateThread.start();
}
};
/**
@@ -143,6 +201,14 @@ public class Window extends JFrame {
evaluateListener,
null
};
/**
* Array of listeners that tell the stop button how to behave
* at a given input tab.
*/
private ActionListener[] stopListeners = {
stopListener,
null
};
/**
* Creates a new window with the given manager.
@@ -152,6 +218,7 @@ public class Window extends JFrame {
public Window(Abacus abacus) {
this();
this.abacus = abacus;
abacus.setWindow(this);
}
/**
@@ -160,25 +227,36 @@ public class Window extends JFrame {
private Window() {
super();
//variables related to when calculations occur
stopCalculating = false;
calculating = true;
lastOutput = "";
//default window properties
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(320, 480);
//initiates input objects
inputField = new JTextField();
inputEnterButton = new JButton(CALC_STRING);
inputStopButton = new JButton(STOP_STRING);
//adds input objects into Panel
inputPanel = new JPanel();
inputPanel.setLayout(new BorderLayout());
inputPanel.add(inputField, BorderLayout.CENTER);
inputPanel.add(inputEnterButton, BorderLayout.SOUTH);
inputPanel.add(inputStopButton, BorderLayout.SOUTH);
inputPanel.add(inputField, BorderLayout.NORTH);
inputPanel.add(inputEnterButton, BorderLayout.CENTER);
//initiates output objects in calculator tab
historyModel = new HistoryTableModel();
historyTable = new JTable(historyModel);
historyScroll = new JScrollPane(historyTable);
lastOutputArea = new JTextArea(lastOutput);
lastOutputArea.setEditable(false);
//adds output objects into Panel
calculationPanel = new JPanel();
calculationPanel.setLayout(new BorderLayout());
calculationPanel.add(historyScroll, BorderLayout.CENTER);
@@ -208,6 +286,8 @@ public class Window extends JFrame {
settingsPanel.add(numberSystemPanel);
settingsPanel.add(functionSelectPanel);
calculating = false;
pane = new JTabbedPane();
pane.add("Calculator", calculationPanel);
pane.add("Settings", settingsPanel);
@@ -215,17 +295,23 @@ public class Window extends JFrame {
int selectionIndex = pane.getSelectedIndex();
boolean enabled = INPUT_ENABLED[selectionIndex];
ActionListener listener = listeners[selectionIndex];
ActionListener stopUsed = stopListeners[selectionIndex];
inputEnterButton.setText(BUTTON_NAMES[selectionIndex]);
inputField.setEnabled(enabled);
inputEnterButton.setEnabled(enabled);
inputStopButton.setEnabled(enabled);
for (ActionListener removingListener : inputEnterButton.getActionListeners()) {
inputEnterButton.removeActionListener(removingListener);
inputField.removeActionListener(removingListener);
}
for(ActionListener removingListener : inputStopButton.getActionListeners()){
inputStopButton.removeActionListener(removingListener);
}
if (listener != null) {
inputEnterButton.addActionListener(listener);
inputField.addActionListener(listener);
inputStopButton.addActionListener(stopUsed);
}
});
add(pane, BorderLayout.CENTER);
@@ -233,6 +319,7 @@ public class Window extends JFrame {
inputEnterButton.addActionListener(evaluateListener);
inputField.addActionListener(evaluateListener);
inputStopButton.addActionListener(stopListener);
historyTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {