1
0
mirror of https://github.com/DanilaFe/abacus synced 2024-12-22 23:40:08 -08:00
This commit is contained in:
Arthur Drobot 2017-08-04 13:30:05 -07:00
commit 80366dbfcd
12 changed files with 594 additions and 103 deletions

View File

@ -2,12 +2,12 @@ package org.nwapw.abacus;
import org.nwapw.abacus.config.Configuration;
import org.nwapw.abacus.fx.AbacusApplication;
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;
@ -15,7 +15,6 @@ import org.nwapw.abacus.tree.TreeNode;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
/**
* The main calculator class. This is responsible
@ -24,10 +23,7 @@ import java.lang.reflect.InvocationTargetException;
*/
public class Abacus {
/**
* The default implementation to use for the number representation.
*/
public static final Class<? extends NumberInterface> DEFAULT_NUMBER = NaiveNumber.class;
public static final NumberImplementation DEFAULT_IMPLEMENTATION = StandardPlugin.IMPLEMENTATION_NAIVE;
/**
* The file used for saving and loading configuration.
*/
@ -147,15 +143,10 @@ public class Abacus {
* @return the resulting number.
*/
public NumberInterface numberFromString(String numberString) {
Class<? extends NumberInterface> toInstantiate =
pluginManager.numberFor(configuration.getNumberImplementation());
if (toInstantiate == null) toInstantiate = DEFAULT_NUMBER;
NumberImplementation toInstantiate =
pluginManager.numberImplementationFor(configuration.getNumberImplementation());
if (toInstantiate == null) toInstantiate = DEFAULT_IMPLEMENTATION;
try {
return toInstantiate.getConstructor(String.class).newInstance(numberString);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
return toInstantiate.instanceForString(numberString);
}
}

View File

@ -1,10 +1,6 @@
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
@ -12,15 +8,6 @@ import java.util.HashMap;
*/
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

@ -24,6 +24,19 @@ import java.util.Set;
*/
public class AbacusController implements PluginListener {
/**
* The title for the apply alert dialog.
*/
private static final String APPLY_MSG_TITLE = "\"Apply\" Needed";
/**
* The text for the header of the apply alert dialog.
*/
private static final String APPLY_MSG_HEADER = "The settings have not been applied.";
/**
* The text for the dialog that is shown if settings haven't been applied.
*/
private static final String APPLY_MSG_TEXT = "You have made changes to the configuration, however, you haven't pressed \"Apply\". " +
"The changes to the configuration will not be present in the calculator until \"Apply\" is pressed.";
/**
* Constant string that is displayed if the text could not be lexed or parsed.
*/
@ -33,6 +46,12 @@ public class AbacusController implements PluginListener {
*/
private static final String ERR_EVAL = "Evaluation Error";
@FXML
private TabPane coreTabPane;
@FXML
private Tab calculateTab;
@FXML
private Tab settingsTab;
@FXML
private TableView<HistoryModel> historyTable;
@FXML
@ -69,8 +88,35 @@ public class AbacusController implements PluginListener {
*/
private ObservableList<ToggleablePlugin> enabledPlugins;
/**
* The abacus instance used for changing the plugin configuration.
*/
private Abacus abacus;
/**
* Boolean which represents whether changes were made to the configuration.
*/
private boolean changesMade;
/**
* Whether an alert about changes to the configuration was already shown.
*/
private boolean reloadAlertShown;
/**
* The alert shown when a press to "apply" is needed.
*/
private Alert reloadAlert;
/**
* Alerts the user if the changes they made
* have not yet been applied.
*/
private void alertIfApplyNeeded(boolean ignorePrevious){
if(changesMade && (!reloadAlertShown || ignorePrevious)) {
reloadAlertShown = true;
reloadAlert.showAndWait();
}
}
@FXML
public void initialize(){
Callback<TableColumn<HistoryModel, String>, TableCell<HistoryModel, String>> cellFactory =
@ -92,6 +138,7 @@ public class AbacusController implements PluginListener {
historyTable.setItems(historyData);
numberImplementationOptions = FXCollections.observableArrayList();
numberImplementationBox.setItems(numberImplementationOptions);
numberImplementationBox.getSelectionModel().selectedIndexProperty().addListener(e -> changesMade = true);
historyTable.getSelectionModel().setCellSelectionEnabled(true);
enabledPlugins = FXCollections.observableArrayList();
enabledPluginView.setItems(enabledPlugins);
@ -102,10 +149,21 @@ public class AbacusController implements PluginListener {
parsedColumn.setCellValueFactory(cell -> cell.getValue().parsedProperty());
outputColumn.setCellFactory(cellFactory);
outputColumn.setCellValueFactory(cell -> cell.getValue().outputProperty());
coreTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if(oldValue.equals(settingsTab)) alertIfApplyNeeded(true);
});
abacus = new Abacus();
abacus.getPluginManager().addListener(this);
abacus.getPluginManager().reload();
changesMade = false;
reloadAlertShown = false;
reloadAlert = new Alert(Alert.AlertType.WARNING);
reloadAlert.setTitle(APPLY_MSG_TITLE);
reloadAlert.setHeaderText(APPLY_MSG_HEADER);
reloadAlert.setContentText(APPLY_MSG_TEXT);
}
@FXML
@ -130,14 +188,17 @@ public class AbacusController implements PluginListener {
inputField.setText("");
}
@FXML
private void performSaveAndReload(){
performSave();
performReload();
changesMade = false;
reloadAlertShown = false;
}
@FXML
private void performReload(){
Configuration configuration = abacus.getConfiguration();
Set<String> disabledPlugins = configuration.getDisabledPlugins();
disabledPlugins.clear();
for(ToggleablePlugin pluginEntry : enabledPlugins){
if(!pluginEntry.isEnabled()) disabledPlugins.add(pluginEntry.getClassName());
}
alertIfApplyNeeded(true);
abacus.getPluginManager().reload();
}
@ -145,20 +206,29 @@ public class AbacusController implements PluginListener {
private void performSave(){
Configuration configuration = abacus.getConfiguration();
configuration.setNumberImplementation(numberImplementationBox.getSelectionModel().getSelectedItem());
Set<String> disabledPlugins = configuration.getDisabledPlugins();
disabledPlugins.clear();
for(ToggleablePlugin pluginEntry : enabledPlugins){
if(!pluginEntry.isEnabled()) disabledPlugins.add(pluginEntry.getClassName());
}
configuration.saveTo(Abacus.CONFIG_FILE);
changesMade = false;
reloadAlertShown = false;
}
@Override
public void onLoad(PluginManager manager) {
Configuration configuration = abacus.getConfiguration();
Set<String> disabledPlugins = configuration.getDisabledPlugins();
numberImplementationOptions.addAll(abacus.getPluginManager().getAllNumbers());
numberImplementationOptions.addAll(abacus.getPluginManager().getAllNumberImplementations());
String actualImplementation = configuration.getNumberImplementation();
String toSelect = (numberImplementationOptions.contains(actualImplementation)) ? actualImplementation : "<default>";
numberImplementationBox.getSelectionModel().select(toSelect);
for(Class<?> pluginClass : abacus.getPluginManager().getLoadedPluginClasses()){
String fullName = pluginClass.getName();
enabledPlugins.add(new ToggleablePlugin(!disabledPlugins.contains(fullName), fullName));
ToggleablePlugin plugin = new ToggleablePlugin(!disabledPlugins.contains(fullName), fullName);
plugin.enabledProperty().addListener(e -> changesMade = true);
enabledPlugins.add(plugin);
}
}

View File

@ -3,25 +3,52 @@ 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

@ -94,8 +94,23 @@ public class NaiveNumber implements NumberInterface {
}
@Override
public int ceiling() {
return (int) Math.ceil(value);
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

View File

@ -83,7 +83,26 @@ public interface NumberInterface {
* Returns the least integer greater than or equal to the number.
* @return the least integer >= the number, if int can hold the value.
*/
int ceiling();
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

@ -12,15 +12,15 @@ public class PreciseNumber implements NumberInterface {
/**
* The number one.
*/
static final PreciseNumber ONE = new PreciseNumber(BigDecimal.ONE);
public static final PreciseNumber ONE = new PreciseNumber(BigDecimal.ONE);
/**
* The number zero.
*/
static final PreciseNumber ZERO = new PreciseNumber(BigDecimal.ZERO);
public static final PreciseNumber ZERO = new PreciseNumber(BigDecimal.ZERO);
/**
* The number ten.
*/
static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
public static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
/**
* The value of the PreciseNumber.
@ -99,8 +99,38 @@ public class PreciseNumber implements NumberInterface {
}
@Override
public int ceiling() {
return (int) Math.ceil(value.doubleValue());
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

View File

@ -0,0 +1,75 @@
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;
/**
* A hash map of operators mapped to their string names.
* The map of the number implementations this plugin provides.
*/
private Map<String, Class<? extends NumberInterface>> numbers;
private Map<String, NumberImplementation> numberImplementations;
/**
* 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<>();
numbers = new HashMap<>();
numberImplementations = new HashMap<>();
enabled = false;
}
@ -74,12 +74,12 @@ public abstract class Plugin {
}
/**
* Gets the list of all numbers provided by this plugin.
* Gets the list of number implementations provided by this plugin.
*
* @return the list of registered numbers.
* @return the list of registered number implementations.
*/
public final Set<String> providedNumbers() {
return numbers.keySet();
public final Set<String> providedNumberImplementations(){
return numberImplementations.keySet();
}
/**
@ -103,13 +103,13 @@ public abstract class Plugin {
}
/**
* Gets the class under the given name.
* Gets the number implementation under the given name.
*
* @param numberName the name of the class.
* @return the class, or null if the plugin doesn't provide it.
* @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.
*/
public final Class<? extends NumberInterface> getNumber(String numberName) {
return numbers.get(numberName);
public final NumberImplementation getNumberImplementation(String name){
return numberImplementations.get(name);
}
/**
@ -158,16 +158,13 @@ public abstract class Plugin {
}
/**
* 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.
* 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.
*/
protected final void registerNumber(String name, Class<? extends NumberInterface> toRegister) {
numbers.put(name, toRegister);
protected final void registerNumberImplementation(String name, NumberImplementation implementation){
numberImplementations.put(name, implementation);
}
/**
@ -194,6 +191,30 @@ 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

@ -33,10 +33,19 @@ public class PluginManager {
*/
private Map<String, Operator> cachedOperators;
/**
* List of registered number implementations that have
* The list of number implementations that have
* been cached, that is, found in a plugin and returned.
*/
private Map<String, Class<? extends NumberInterface>> cachedNumbers;
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;
/**
* List of all functions loaded by the plugins.
*/
@ -46,9 +55,9 @@ public class PluginManager {
*/
private Set<String> allOperators;
/**
* List of all numbers loaded by the plugins.
* List of all the number implementations loaded by the plugins.
*/
private Set<String> allNumbers;
private Set<String> allNumberImplementations;
/**
* The list of plugin listeners attached to this instance.
*/
@ -68,10 +77,12 @@ public class PluginManager {
plugins = new HashSet<>();
cachedFunctions = new HashMap<>();
cachedOperators = new HashMap<>();
cachedNumbers = new HashMap<>();
cachedNumberImplementations = new HashMap<>();
cachedInterfaceImplementations = new HashMap<>();
cachedPi = new HashMap<>();
allFunctions = new HashSet<>();
allOperators = new HashSet<>();
allNumbers = new HashSet<>();
allNumberImplementations = new HashSet<>();
listeners = new HashSet<>();
}
@ -87,12 +98,13 @@ 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> 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) {
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) {
if (cache.containsKey(name)) return cache.get(name);
T loadedValue = null;
@ -128,13 +140,51 @@ public class PluginManager {
}
/**
* Gets a numer implementation under the given name.
*
* Gets the number implementation under the given name.
* @param name the name of the implementation.
* @return the implementation class
* @return the implementation.
*/
public Class<? extends NumberInterface> numberFor(String name) {
return searchCached(plugins, cachedNumbers, Plugin::providedNumbers, Plugin::getNumber, name);
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;
}
/**
@ -176,7 +226,7 @@ public class PluginManager {
if(disabledPlugins.contains(plugin.getClass().getName())) continue;
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumbers.addAll(plugin.providedNumbers());
allNumberImplementations.addAll(plugin.providedNumberImplementations());
}
listeners.forEach(e -> e.onLoad(this));
}
@ -193,10 +243,13 @@ public class PluginManager {
}
cachedFunctions.clear();
cachedOperators.clear();
cachedNumbers.clear();
cachedNumberImplementations.clear();
cachedInterfaceImplementations.clear();
cachedPi.clear();
allFunctions.clear();
allOperators.clear();
allNumbers.clear();
allNumberImplementations.clear();
listeners.forEach(e -> e.onUnload(this));
}
/**
@ -226,12 +279,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> getAllNumbers() {
return allNumbers;
public Set<String> getAllNumberImplementations(){
return allNumberImplementations;
}
/**

View File

@ -19,7 +19,7 @@ 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>>();
private static final HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>> FACTORIAL_LISTS = new HashMap<>();
/**
* The addition operator, +
@ -106,7 +106,9 @@ 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;
return params.length == 1
&& params[0].fractionalPart().compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0
&& params[0].signum() >= 0;
}
@Override
@ -191,7 +193,7 @@ public class StandardPlugin extends Plugin {
//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())), right = maxError;
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++;
@ -299,6 +301,160 @@ 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);
}
};
/**
* The cosine function (the argument is in radians).
*/
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]));
}
};
/**
* The tangent function (the argument is in radians).
*/
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]));
}
};
/**
* The secant function (the argument is in radians).
*/
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]));
}
};
/**
* The cosecant function (the argument is in radians).
*/
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]));
}
};
/**
* The cotangent function (the argument is in radians).
*/
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);
}
@ -331,8 +487,8 @@ public class StandardPlugin extends Plugin {
@Override
public void onEnable() {
registerNumber("naive", NaiveNumber.class);
registerNumber("precise", PreciseNumber.class);
registerNumberImplementation("naive", IMPLEMENTATION_NAIVE);
registerNumberImplementation("precise", IMPLEMENTATION_PRECISE);
registerOperator("+", OP_ADD);
registerOperator("-", OP_SUBTRACT);
@ -346,6 +502,12 @@ 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
@ -353,13 +515,20 @@ 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<>());
factorialLists.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
factorialLists.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
if(!FACTORIAL_LISTS.containsKey(numberClass)){
FACTORIAL_LISTS.put(numberClass, new ArrayList<>());
FACTORIAL_LISTS.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
FACTORIAL_LISTS.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
}
ArrayList<NumberInterface> list = factorialLists.get(numberClass);
ArrayList<NumberInterface> list = FACTORIAL_LISTS.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)));
@ -368,4 +537,36 @@ public class StandardPlugin extends Plugin {
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

@ -7,12 +7,13 @@
<?import javafx.scene.text.Text?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.FlowPane?>
<BorderPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="org.nwapw.abacus.fx.AbacusController">
<center>
<TabPane>
<Tab text="Calculator" closable="false">
<TabPane fx:id="coreTabPane">
<Tab fx:id="calculateTab" text="Calculator" closable="false">
<BorderPane>
<center>
<TableView fx:id="historyTable">
@ -41,7 +42,7 @@
</bottom>
</BorderPane>
</Tab>
<Tab text="Settings" closable="false">
<Tab fx:id="settingsTab" text="Settings" closable="false">
<GridPane hgap="10" vgap="10">
<padding><Insets left="10" right="10" top="10" bottom="10"/></padding>
<Label text="Number Implementation" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
@ -49,10 +50,11 @@
<ListView fx:id="enabledPluginView"
GridPane.rowIndex="1" GridPane.columnIndex="0"
GridPane.columnSpan="2" maxHeight="100"/>
<HBox GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2" spacing="10">
<FlowPane GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2" hgap="10" vgap="10">
<Button text="Apply" onAction="#performSave"/>
<Button text="Reload" onAction="#performReload"/>
</HBox>
<Button text="Reload Plugins" onAction="#performReload"/>
<Button text="Apply and Reload" onAction="#performSaveAndReload"/>
</FlowPane>
</GridPane>
</Tab>
</TabPane>