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

Compare commits

..

5 Commits

Author SHA1 Message Date
Riley Jones
f8bf60f383 Fix exp function 2017-08-04 13:52:41 -07:00
Riley Jones
4369eba107 Allow all standard functions to end early 2017-08-04 13:45:29 -07:00
Riley Jones
eff7be0204 StandardPlugin uses null 2017-08-03 23:59:23 -07:00
Riley Jones
9d5f9d901c Plugin fixes 2017-08-03 15:16:26 -07:00
Riley Jones
dad546c5b5 Add stop button 2017-08-03 14:04:09 -07:00
11 changed files with 220 additions and 283 deletions

View File

@@ -57,7 +57,7 @@ public class Abacus {
* Creates a new instance of the Abacus calculator.
*/
public Abacus() {
pluginManager = new PluginManager(this);
pluginManager = new PluginManager();
numberReducer = new NumberReducer(this);
configuration = new Configuration(CONFIG_FILE);
configuration.saveTo(CONFIG_FILE);

View File

@@ -5,9 +5,6 @@ import com.moandjiezana.toml.TomlWriter;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* The configuration object that stores
@@ -15,38 +12,26 @@ import java.util.Set;
*/
public class Configuration {
/**
* The defaults TOML string.
*/
private static final String DEFAULT_CONFIG =
"numberImplementation = \"naive\"\n" +
"disabledPlugins = []";
/**
* The defaults TOML object, parsed from the string.
*/
private static final Toml DEFAULT_TOML = new Toml().read(DEFAULT_CONFIG);
/**
* The TOML writer used to write this configuration to a file.
*/
private static final TomlWriter TOML_WRITER = new TomlWriter();
/**
* The TOML reader used to load this config from a file.
*/
private static final Toml TOML_READER = new Toml();
/**
* The implementation of the number that should be used.
*/
private String numberImplementation = "<default>";
/**
* The list of disabled plugins in this Configuration.
*/
private Set<String> disabledPlugins = new HashSet<>();
private String numberImplementation = "naive";
/**
* Creates a new configuration with the given values.
* @param numberImplementation the number implementation, like "naive" or "precise"
* @param disabledPlugins the list of disabled plugins.
*/
public Configuration(String numberImplementation, String[] disabledPlugins){
public Configuration(String numberImplementation){
this.numberImplementation = numberImplementation;
this.disabledPlugins.addAll(Arrays.asList(disabledPlugins));
}
/**
@@ -55,7 +40,7 @@ public class Configuration {
*/
public Configuration(File fromFile){
if(!fromFile.exists()) return;
copyFrom(new Toml(DEFAULT_TOML).read(fromFile).to(Configuration.class));
copyFrom(TOML_READER.read(fromFile).to(Configuration.class));
}
/**
@@ -64,7 +49,6 @@ public class Configuration {
*/
public void copyFrom(Configuration otherConfiguration){
this.numberImplementation = otherConfiguration.numberImplementation;
this.disabledPlugins.addAll(otherConfiguration.disabledPlugins);
}
/**
@@ -96,13 +80,4 @@ public class Configuration {
public void setNumberImplementation(String numberImplementation) {
this.numberImplementation = numberImplementation;
}
/**
* Gets the list of disabled plugins.
* @return the list of disabled plugins.
*/
public Set<String> getDisabledPlugins() {
return disabledPlugins;
}
}

View File

@@ -1,42 +1,23 @@
package org.nwapw.abacus.fx;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.text.Text;
import javafx.util.Callback;
import javafx.util.StringConverter;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.config.Configuration;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.plugin.PluginListener;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.tree.TreeNode;
import java.util.Set;
/**
* The controller for the abacus FX UI, responsible
* for all the user interaction.
*/
public class AbacusController implements PluginListener {
public class AbacusController {
/**
* 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.
*/
@@ -45,13 +26,10 @@ public class AbacusController implements PluginListener {
* Constant string that is displayed if the tree could not be reduced.
*/
private static final String ERR_EVAL = "Evaluation Error";
@FXML
private TabPane coreTabPane;
@FXML
private Tab calculateTab;
@FXML
private Tab settingsTab;
/**
* Constant string that is displayed if the calculations are stopped before they are done.
*/
private static final String ERR_STOP = "Stopped";
@FXML
private TableView<HistoryModel> historyTable;
@FXML
@@ -68,8 +46,6 @@ public class AbacusController implements PluginListener {
private Button inputButton;
@FXML
private ComboBox<String> numberImplementationBox;
@FXML
private ListView<ToggleablePlugin> enabledPluginView;
/**
* The list of history entries, created by the users.
@@ -83,158 +59,109 @@ public class AbacusController implements PluginListener {
private ObservableList<String> numberImplementationOptions;
/**
* The list of plugin objects that can be toggled on and off,
* and, when reloaded, get added to the plugin manager's black list.
* Thread used for calculating.
*/
private ObservableList<ToggleablePlugin> enabledPlugins;
private Thread calcThread;
/**
* The abacus instance used for changing the plugin configuration.
* Checks whether the calculator is calculating.
*/
private boolean calculating;
/**
* Seconds delayed for timer;
*/
private double delay = 0;
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 =
param -> new CopyableCell<>();
Callback<ListView<ToggleablePlugin>, ListCell<ToggleablePlugin>> pluginCellFactory =
param -> new CheckBoxListCell<>(ToggleablePlugin::enabledProperty, new StringConverter<ToggleablePlugin>() {
@Override
public String toString(ToggleablePlugin object) {
return object.getClassName().substring(object.getClassName().lastIndexOf('.') + 1);
}
@Override
public ToggleablePlugin fromString(String string) {
return new ToggleablePlugin(true, string);
}
});
historyData = FXCollections.observableArrayList();
historyTable.setItems(historyData);
numberImplementationOptions = FXCollections.observableArrayList();
numberImplementationBox.setItems(numberImplementationOptions);
numberImplementationBox.getSelectionModel().selectedIndexProperty().addListener(e -> changesMade = true);
numberImplementationBox.valueProperty().addListener((observable, oldValue, newValue)
-> {
abacus.getConfiguration().setNumberImplementation(newValue);
abacus.getConfiguration().saveTo(Abacus.CONFIG_FILE);
});
historyTable.getSelectionModel().setCellSelectionEnabled(true);
enabledPlugins = FXCollections.observableArrayList();
enabledPluginView.setItems(enabledPlugins);
enabledPluginView.setCellFactory(pluginCellFactory);
inputColumn.setCellFactory(cellFactory);
inputColumn.setCellValueFactory(cell -> cell.getValue().inputProperty());
parsedColumn.setCellFactory(cellFactory);
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);
numberImplementationOptions.addAll(abacus.getPluginManager().getAllNumbers());
String actualImplementation = abacus.getConfiguration().getNumberImplementation();
String toSelect = (numberImplementationOptions.contains(actualImplementation)) ? actualImplementation : "naive";
numberImplementationBox.getSelectionModel().select(toSelect);
}
@FXML
private void performCalculation(){
inputButton.setDisable(true);
TreeNode constructedTree = abacus.parseString(inputField.getText());
if(constructedTree == null){
outputText.setText(ERR_SYNTAX);
inputButton.setDisable(false);
return;
}
NumberInterface evaluatedNumber = abacus.evaluateTree(constructedTree);
if(evaluatedNumber == null){
outputText.setText(ERR_EVAL);
inputButton.setDisable(false);
return;
}
outputText.setText(evaluatedNumber.toString());
historyData.add(new HistoryModel(inputField.getText(), constructedTree.toString(), evaluatedNumber.toString()));
Runnable calculator = new Runnable(){
public void run() {
if(delay>0) {
Runnable timer = new Runnable() {
public void run() {
long gap = (long) (delay * 1000);
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime <= gap) {
}
stopCalculation();
}
};
Thread maxTime = new Thread(timer);
maxTime.setName("maxTime");
maxTime.start();
}
calculating = true;
Platform.runLater(() -> inputButton.setDisable(true));
TreeNode constructedTree = abacus.parseString(inputField.getText());
if (constructedTree == null) {
Platform.runLater(() ->outputText.setText(ERR_SYNTAX));
Platform.runLater(() -> inputButton.setDisable(false));
//return;
}else {
NumberInterface evaluatedNumber = abacus.evaluateTree(constructedTree);
if (evaluatedNumber == null) {
if(Thread.currentThread().isInterrupted()){
Platform.runLater(() -> outputText.setText(ERR_STOP));
Platform.runLater(() -> inputButton.setDisable(false));
}else {
Platform.runLater(() -> outputText.setText(ERR_EVAL));
Platform.runLater(() -> inputButton.setDisable(false));
//return;
}
} else {
Platform.runLater(() -> outputText.setText(evaluatedNumber.toString()));
inputButton.setDisable(false);
inputField.setText("");
historyData.add(new HistoryModel(inputField.getText(), constructedTree.toString(), evaluatedNumber.toString()));
Platform.runLater(() -> inputButton.setDisable(false));
Platform.runLater(() -> inputField.setText(""));
}
}
calculating = false;
}
};
if(!calculating) {
calcThread = new Thread(calculator);
calcThread.setName("calcThread");
calcThread.start();
}
}
@FXML
private void performSaveAndReload(){
performSave();
performReload();
changesMade = false;
reloadAlertShown = false;
private void stopCalculation(){
calcThread.interrupt();
calculating = false;
//Platform.runLater(() ->inputButton.setDisable(false));
}
@FXML
private void performReload(){
alertIfApplyNeeded(true);
abacus.getPluginManager().reload();
}
@FXML
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());
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();
ToggleablePlugin plugin = new ToggleablePlugin(!disabledPlugins.contains(fullName), fullName);
plugin.enabledProperty().addListener(e -> changesMade = true);
enabledPlugins.add(plugin);
}
}
@Override
public void onUnload(PluginManager manager) {
enabledPlugins.clear();
numberImplementationOptions.clear();
}
}

View File

@@ -1,29 +0,0 @@
package org.nwapw.abacus.fx;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
public class ToggleablePlugin {
private final BooleanProperty enabled;
private final String className;
public ToggleablePlugin(boolean enabled, String className){
this.enabled = new SimpleBooleanProperty();
this.enabled.setValue(enabled);
this.className = className;
}
public BooleanProperty enabledProperty() {
return enabled;
}
public boolean isEnabled() {
return enabled.get();
}
public String getClassName() {
return className;
}
}

View File

@@ -89,7 +89,7 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
if (!(otherMatchType == TokenType.OP || otherMatchType == TokenType.FUNCTION)) break;
if (otherMatchType == TokenType.OP) {
int otherPrecedence = precedenceMap.get(otherMatch.getContent());
int otherPrecedence = precedenceMap.get(match.getContent());
if (otherPrecedence < precedence ||
(associativity == OperatorAssociativity.RIGHT && otherPrecedence == precedence)) {
break;

View File

@@ -1,6 +1,5 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.number.NumberInterface;
@@ -53,17 +52,11 @@ public class PluginManager {
* The list of plugin listeners attached to this instance.
*/
private Set<PluginListener> listeners;
/**
* The abacus instance used to access other
* components of the application.
*/
private Abacus abacus;
/**
* Creates a new plugin manager.
*/
public PluginManager(Abacus abacus) {
this.abacus = abacus;
public PluginManager() {
loadedPluginClasses = new HashSet<>();
plugins = new HashSet<>();
cachedFunctions = new HashMap<>();
@@ -167,13 +160,8 @@ public class PluginManager {
* Loads all the plugins in the PluginManager.
*/
public void load() {
Set<String> disabledPlugins = abacus.getConfiguration().getDisabledPlugins();
for (Plugin plugin : plugins) plugin.enable();
for (Plugin plugin : plugins) {
if(disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.enable();
}
for (Plugin plugin : plugins) {
if(disabledPlugins.contains(plugin.getClass().getName())) continue;
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumbers.addAll(plugin.providedNumbers());
@@ -185,18 +173,11 @@ public class PluginManager {
* Unloads all the plugins in the PluginManager.
*/
public void unload() {
listeners.forEach(e -> e.onUnload(this));
Set<String> disabledPlugins = abacus.getConfiguration().getDisabledPlugins();
for (Plugin plugin : plugins) {
if(disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.disable();
}
cachedFunctions.clear();
cachedOperators.clear();
cachedNumbers.clear();
for (Plugin plugin : plugins) plugin.disable();
allFunctions.clear();
allOperators.clear();
allNumbers.clear();
listeners.forEach(e -> e.onUnload(this));
}
/**
@@ -204,7 +185,7 @@ public class PluginManager {
*/
public void reload() {
unload();
load();
reload();
}
/**
@@ -252,12 +233,4 @@ public class PluginManager {
listeners.remove(listener);
}
/**
* Gets a list of all the plugin class files that have been
* added to the plugin manager.
* @return the list of all the added plugin classes.
*/
public Set<Class<?>> getLoadedPluginClasses() {
return loadedPluginClasses;
}
}

View File

@@ -31,9 +31,13 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface sum = params[0];
for (int i = 1; i < params.length; i++) {
sum = sum.add(params[i]);
if(Thread.currentThread().isInterrupted())
return null;
}
return sum;
}
@@ -49,7 +53,10 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
return params[0].subtract(params[1]);
}
});
/**
@@ -63,6 +70,8 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
return params[0].negate();
}
});
@@ -77,9 +86,13 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface product = params[0];
for (int i = 1; i < params.length; i++) {
product = product.multiply(params[i]);
if(Thread.currentThread().isInterrupted())
return null;
}
return product;
}
@@ -95,6 +108,8 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
return params[0].divide(params[1]);
}
});
@@ -110,15 +125,19 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
if (params[0].signum() == 0) {
return (new NaiveNumber(1)).promoteTo(params[0].getClass());
}
NumberInterface factorial = params[0];
NumberInterface multiplier = params[0];
//It is necessary to later prevent calls of factorial on anything but non-negative integers.
while ((multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClass()))).signum() == 1) {
while (!Thread.currentThread().isInterrupted()&&(multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClass())))!=null&&multiplier.signum() == 1) {
factorial = factorial.multiply(multiplier);
}
if(Thread.currentThread().isInterrupted())
return null;
return factorial;
/*if(!storedList.containsKey(params[0].getClass())){
storedList.put(params[0].getClass(), new ArrayList<NumberInterface>());
@@ -138,7 +157,12 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return FUNCTION_EXP.apply(FUNCTION_LN.apply(params[0]).multiply(params[1]));
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface check;
if((check = FUNCTION_EXP.apply(FUNCTION_LN.apply(params[0])))!=null&&(check = check.multiply(params[1]))!=null)
return check;
return null;
}
});
/**
@@ -152,6 +176,8 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass()));
}
};
@@ -166,14 +192,17 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
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){
NumberInterface check;
while((check = FUNCTION_ABS.apply(currentTerm))!=null && (check.compareTo(maxError) > 0)){
n++;
currentTerm = currentTerm.multiply(params[0]).divide((new NaiveNumber(n)).promoteTo(params[0].getClass()));
sum = sum.add(currentTerm);
if(Thread.currentThread().isInterrupted()||(currentTerm = currentTerm.multiply(params[0]))==null||(currentTerm = currentTerm.divide((new NaiveNumber(n)).promoteTo(params[0].getClass())))==null||(sum = (sum.add(currentTerm)))==null)
return null;
}
return sum;
}
@@ -182,18 +211,28 @@ 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())), right = maxError;
NumberInterface check;
if((check =intPow(new NaiveNumber(3).promoteTo(params[0].getClass()),params[0].getClass(),(new NaiveNumber(params[0].ceiling())).promoteTo(params[0].getClass())))==null)
return null;
NumberInterface left = params[0].multiply(check), right = maxError;
do{
sum = sum.add(nextNumerator.divide(factorial(params[0].getClass(), n+1)));
if((check = factorial(params[0].getClass(),n+1))==null||(check = nextNumerator.divide(check))==null||(sum = sum.add(check))==null)
return null;
n++;
nextNumerator = nextNumerator.multiply(params[0]);
left = left.multiply(params[0]);
if((nextNumerator = nextNumerator.multiply(params[0]))==null)
return null;
if((left = left.multiply(params[0]))==null)
return null;
NumberInterface nextN = (new NaiveNumber(n+1)).promoteTo(params[0].getClass());
right = right.multiply(nextN);
if((right = right.multiply(nextN))==null)
return null;
//System.out.println(left + ", " + right);
}
while(left.compareTo(right) > 0);
while(!Thread.currentThread().isInterrupted()&&left.compareTo(right) > 0);
//System.out.println(n+1);
if(Thread.currentThread().isInterrupted())
return null;
return sum;
}
}
@@ -209,26 +248,32 @@ public class StandardPlugin extends Plugin {
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface param = params[0];
int powersOf2 = 0;
while (FUNCTION_ABS.apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))).compareTo((new NaiveNumber(0.1)).promoteTo(param.getClass())) >= 0) {
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() == 1) {
NumberInterface check;
while (!Thread.currentThread().isInterrupted()&&(check = FUNCTION_ABS.apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))))!=null&&(check.compareTo((new NaiveNumber(0.1)).promoteTo(param.getClass()))) >= 0) {
if ((check = param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())))!=null&&check.signum() == 1) {
param = param.divide(new NaiveNumber(2).promoteTo(param.getClass()));
powersOf2++;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) {
if ((check = param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())))==null||check.signum() != 1) {
break;
//No infinite loop for you.
}
} else {
param = param.multiply(new NaiveNumber(2).promoteTo(param.getClass()));
powersOf2--;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != -1) {
if ((check = param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())))==null||check.signum() != 1) {
break;
//No infinite loop for you.
}
}
}
return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClass())).add(getLogPartialSum(param));
NumberInterface check2;
if(!Thread.currentThread().isInterrupted()&&(check = getLog2(param))!=null&&(check = check.multiply((new NaiveNumber(powersOf2).promoteTo(param.getClass()))))!=null&&(check2 = getLogPartialSum(param))!=null&&(check = check.add(check2))!=null)
return check;
return null;
}
/**
@@ -238,16 +283,23 @@ public class StandardPlugin extends Plugin {
* @return the partial sum.
*/
private NumberInterface getLogPartialSum(NumberInterface x) {
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface maxError = getMaxError(x);
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;
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) {
NumberInterface check;
while (!Thread.currentThread().isInterrupted()&&(check = FUNCTION_ABS.apply(currentTerm))!=null&&check.compareTo(maxError) > 0) {
n++;
currentNumerator = currentNumerator.multiply(x).negate();
if((currentNumerator = currentNumerator.multiply(x))==null||(currentNumerator = currentNumerator.negate())==null)
return null;
currentTerm = currentNumerator.divide(new NaiveNumber(n).promoteTo(x.getClass()));
sum = sum.add(currentTerm);
}
if(Thread.currentThread().isInterrupted())
return null;
return sum;
}
@@ -257,6 +309,8 @@ public class StandardPlugin extends Plugin {
* @return the value of log(2) with the appropriate precision.
*/
private NumberInterface getLog2(NumberInterface number) {
if(Thread.currentThread().isInterrupted())
return null;
NumberInterface maxError = getMaxError(number);
//NumberInterface errorBound = (new NaiveNumber(1)).promoteTo(number.getClass());
//We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n)
@@ -265,13 +319,17 @@ public class StandardPlugin extends Plugin {
NumberInterface a = (new NaiveNumber(1)).promoteTo(number.getClass()), b = a, c = a;
NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClass());
int n = 0;
while (a.compareTo(maxError) >= 1) {
while (!Thread.currentThread().isInterrupted()&&a.compareTo(maxError) >= 1) {
n++;
a = a.divide((new NaiveNumber(3)).promoteTo(number.getClass()));
b = b.divide((new NaiveNumber(4)).promoteTo(number.getClass()));
c = NaiveNumber.ONE.promoteTo(number.getClass()).divide((new NaiveNumber(n)).promoteTo(number.getClass()));
sum = sum.add(a.add(b).multiply(c));
NumberInterface check;
if(a==null||(check = a.add(b))==null||(check = check.multiply(c))==null||(sum = sum.add(check))==null)
return null;
}
if(Thread.currentThread().isInterrupted())
return null;
return sum;
}
};
@@ -345,6 +403,8 @@ public class StandardPlugin extends Plugin {
}
public static NumberInterface factorial(Class<? extends NumberInterface> numberClass, int n){
if(Thread.currentThread().isInterrupted())
return null;
if(!factorialLists.containsKey(numberClass)){
factorialLists.put(numberClass, new ArrayList<>());
factorialLists.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass));
@@ -352,11 +412,34 @@ public class StandardPlugin extends Plugin {
}
ArrayList<NumberInterface> list = factorialLists.get(numberClass);
if(n >= list.size()){
while(list.size() < n + 16){
while(!Thread.currentThread().isInterrupted()&&list.size() < n + 16){
list.add(list.get(list.size()-1).multiply(new NaiveNumber(list.size()).promoteTo(numberClass)));
}
}
if(Thread.currentThread().isInterrupted())
return null;
return list.get(n);
}
public static NumberInterface intPow(NumberInterface number, Class<? extends NumberInterface> numberClass,NumberInterface exponent) {
if(Thread.currentThread().isInterrupted())
return null;
if (exponent.compareTo((new NaiveNumber(0)).promoteTo(numberClass))==0) {
return (new NaiveNumber(1)).promoteTo(numberClass);
}
boolean takeReciprocal = exponent.compareTo((new NaiveNumber(0)).promoteTo(numberClass))<0;
exponent = FUNCTION_ABS.apply(exponent);
NumberInterface power = number;
for(NumberInterface currentExponent =(new NaiveNumber(1)).promoteTo(numberClass);currentExponent.compareTo(exponent)<0;currentExponent = currentExponent.add((new NaiveNumber(1)).promoteTo(numberClass))){
power = power.multiply(number);
if(Thread.currentThread().isInterrupted())
return null;
}
if (takeReciprocal) {
power = (new NaiveNumber(1)).promoteTo(numberClass).divide(power);
}
if(Thread.currentThread().isInterrupted())
return null;
return power;
}
}

View File

@@ -92,10 +92,15 @@ public class BinaryNode extends TreeNode {
@Override
public <T> T reduce(Reducer<T> reducer) {
if(Thread.currentThread().isInterrupted())
return null;
T leftReduce = left.reduce(reducer);
T rightReduce = right.reduce(reducer);
if (leftReduce == null || rightReduce == null) return null;
return reducer.reduceNode(this, leftReduce, rightReduce);
T a = reducer.reduceNode(this, leftReduce, rightReduce);
if(Thread.currentThread().isInterrupted())
return null;
return a;
}
@Override

View File

@@ -62,12 +62,17 @@ public class FunctionNode extends TreeNode {
@Override
public <T> T reduce(Reducer<T> reducer) {
if(Thread.currentThread().isInterrupted())
return null;
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;
if (Thread.currentThread().isInterrupted()||reducedChildren[i] == null) return null;
}
return reducer.reduceNode(this, reducedChildren);
T a = reducer.reduceNode(this, reducedChildren);
if(Thread.currentThread().isInterrupted())
return null;
return a;
}
@Override

View File

@@ -33,9 +33,14 @@ public class UnaryNode extends TreeNode {
@Override
public <T> T reduce(Reducer<T> reducer) {
if(Thread.currentThread().isInterrupted())
return null;
Object reducedChild = applyTo.reduce(reducer);
if (reducedChild == null) return null;
return reducer.reduceNode(this, reducedChild);
T a = reducer.reduceNode(this, reducedChild);
if(Thread.currentThread().isInterrupted())
return null;
return a;
}
/**

View File

@@ -7,13 +7,12 @@
<?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 fx:id="coreTabPane">
<Tab fx:id="calculateTab" text="Calculator" closable="false">
<TabPane>
<Tab text="Calculator" closable="false">
<BorderPane>
<center>
<TableView fx:id="historyTable">
@@ -38,23 +37,17 @@
<TextField fx:id="inputField" onAction="#performCalculation"/>
<Button fx:id="inputButton" text="Calculate" maxWidth="Infinity"
onAction="#performCalculation"/>
<Button fx:id="stopButton" text="Stop" maxWidth="Infinity"
onAction="#stopCalculation"/>
</VBox>
</bottom>
</BorderPane>
</Tab>
<Tab fx:id="settingsTab" text="Settings" closable="false">
<Tab 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"/>
<ComboBox fx:id="numberImplementationBox" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<ListView fx:id="enabledPluginView"
GridPane.rowIndex="1" GridPane.columnIndex="0"
GridPane.columnSpan="2" maxHeight="100"/>
<FlowPane GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2" hgap="10" vgap="10">
<Button text="Apply" onAction="#performSave"/>
<Button text="Reload Plugins" onAction="#performReload"/>
<Button text="Apply and Reload" onAction="#performSaveAndReload"/>
</FlowPane>
</GridPane>
</Tab>
</TabPane>