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

Compare commits

...

55 Commits

Author SHA1 Message Date
1c448048f2 Fix typos created in removing the promoteTo calls. 2017-08-09 19:23:44 -07:00
fd21014c39 Phase out as many promoteTo calls as possible. 2017-08-09 19:04:32 -07:00
021e569491 Make the C in nCr capital. 2017-08-09 17:15:12 -07:00
e6f5af3727 Add optimization to NPR. 2017-08-09 12:47:22 -07:00
4e042bd0eb Implement two combinatorics operators. 2017-08-09 12:34:02 -07:00
d6f4838f05 Add a random function. 2017-08-09 11:51:12 -07:00
61475a24d9 Fix the weird scroll bars. 2017-08-09 11:22:01 -07:00
c498a5b643 Merge branch 'function-doc' 2017-08-09 11:10:00 -07:00
5e3daaed43 Rescan the plugins folder. 2017-08-09 11:02:21 -07:00
b99ad5a09a Add plugin removal from the plugin manager. 2017-08-09 10:30:04 -07:00
ff8701a7bf Deprecate the promotion functions. 2017-08-08 15:29:19 -07:00
33b175a3c6 Fix some documentation glitches. 2017-08-08 14:39:41 -07:00
c95a6df304 Change the sorting order. 2017-08-08 14:26:04 -07:00
3316f02e2b Add documentation. 2017-08-08 14:18:14 -07:00
6767a0e4aa Change the width property bound to the width. 2017-08-08 14:18:08 -07:00
400e4578a0 Add documentation browsing to the abacus controller. 2017-08-08 13:49:19 -07:00
9d92d0eebb Add registering documentation to plugins. 2017-08-08 13:49:04 -07:00
fdcf2b5c6d Fix documentation loading code. 2017-08-08 13:47:03 -07:00
8c3de54d0c Add a matches function. 2017-08-08 13:46:54 -07:00
5a57544067 Add a plugin registration function to Plugins. 2017-08-08 11:27:59 -07:00
61f40c72aa Add a registered documentation set. 2017-08-08 11:09:46 -07:00
ea5ff08c09 Add documentation type for a documentation entry. 2017-08-08 10:54:36 -07:00
5f80c0bf14 Add a documentation class. 2017-08-08 10:50:30 -07:00
7dcc80fcae Merge branch 'master' of github.com:DanilaFe/abacus 2017-08-08 10:19:45 -07:00
d10536155b Make the map private. 2017-08-08 10:13:35 -07:00
536cac7b23 Convert Reducer interface to Kotlin. 2017-08-08 10:11:30 -07:00
Arthur Drobot
b6e4c6d2ea Merge branch 'sig-fig' 2017-08-08 09:46:46 -07:00
Arthur Drobot
f8b3559cec Add some tests to pow. 2017-08-08 09:45:13 -07:00
Arthur Drobot
4cf4ba98a8 Adjust unit tests. Set the number of significant figures in the output to 50. 2017-08-08 09:27:10 -07:00
12710c625b Add missing comments. 2017-08-07 22:48:56 -07:00
e71b037195 Switch the ToggleablePlugin class to Kotlin to avoid boilerplate. 2017-08-07 22:44:16 -07:00
fe92929856 Switch HistoryModel to Kotlin to avoid boilerplate. 2017-08-07 22:39:35 -07:00
e61cfdca46 Create a documentation object class. 2017-08-07 22:30:32 -07:00
ff7d90967e Fix toString errors failing unit tests. 2017-08-07 19:22:35 -07:00
355a91d690 Rewrite the Operator in Kotlin. 2017-08-07 19:16:51 -07:00
5f0fba15eb Add comments to the newly created Kotlin implementations. 2017-08-07 19:11:13 -07:00
3bdc0e2ae5 Rewrite tree nodes in Kotlin. Documentation pending. 2017-08-07 18:57:43 -07:00
Arthur Drobot
68fbcd2d7c Modify exp to use the non-alternating series and take a reciprocal in the case of a negative argument. 2017-08-07 18:13:18 -07:00
Arthur Drobot
ed92b382f0 Rewrite precise number to limit significant figures rather than decimal places. Add getMaxError to NumberInterface; modify numbers and StandardPlugin appropriately. 2017-08-07 17:58:18 -07:00
e54b5cdd66 Add Kotlin support to gradle. 2017-08-07 17:33:56 -07:00
fd87cb66a3 Merge branch 'master' of github.com:DanilaFe/abacus 2017-08-07 14:27:29 -07:00
200f4c7288 Add a filter. 2017-08-07 14:12:41 -07:00
Arthur Drobot
1cd544e712 Merge branch 'master' of https://github.com/DanilaFe/abacus 2017-08-07 14:08:17 -07:00
Arthur Drobot
a8c70a6bbe Add checking of negative bases raised to non-integer powers in matchesParams in OP_CARET. 2017-08-07 14:05:15 -07:00
f28e915c9a Fix not clearing unloaded plugins. 2017-08-07 13:55:24 -07:00
7a0863380a Add a list of functions to the controller. 2017-08-07 13:55:13 -07:00
Arthur Drobot
8a9df051cf Optimize pow for integer bases. 2017-08-07 13:43:12 -07:00
Arthur Drobot
4eda15b3fb Modify some functions in PreciseNumber for consistency. 2017-08-07 13:41:45 -07:00
c9e0d4f8d3 Fix broken documentation,. 2017-08-07 11:18:01 -07:00
213d7af10b Merge branch 'remove-caching'
# Conflicts:
#	src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java
2017-08-07 11:14:11 -07:00
585a3839c1 Merge branch 'time-limit' 2017-08-07 11:12:12 -07:00
Arthur Drobot
d0ccb8b625 Improve some comments of NumberInterface functions. 2017-08-07 10:54:27 -07:00
Arthur Drobot
7d5efa1fe6 Add fromInt function into StandardPlugin and replace existing instantiations and promotions of NaiveNumbers with integer values with fromInt calls. 2017-08-07 10:33:16 -07:00
35254d3e99 Rename getPi to piFor. 2017-08-06 21:56:49 -07:00
44f018060d Remove the useless caching in the plugin manager and the maps in plugins 2017-08-06 21:55:09 -07:00
32 changed files with 786 additions and 864 deletions

View File

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

View File

@@ -0,0 +1,7 @@
package org.nwapw.abacus.function;
public enum DocumentationType {
FUNCTION
}

View File

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

View File

@@ -5,7 +5,9 @@ import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue; import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxListCell; import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.text.Text; import javafx.scene.text.Text;
@@ -13,6 +15,8 @@ import javafx.util.Callback;
import javafx.util.StringConverter; import javafx.util.StringConverter;
import org.nwapw.abacus.Abacus; import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.config.Configuration; import org.nwapw.abacus.config.Configuration;
import org.nwapw.abacus.function.Documentation;
import org.nwapw.abacus.function.DocumentationType;
import org.nwapw.abacus.number.ComputationInterruptedException; import org.nwapw.abacus.number.ComputationInterruptedException;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.plugin.ClassFinder; import org.nwapw.abacus.plugin.ClassFinder;
@@ -23,7 +27,10 @@ import org.nwapw.abacus.tree.TreeNode;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
/** /**
@@ -72,6 +79,8 @@ public class AbacusController implements PluginListener {
@FXML @FXML
private Tab settingsTab; private Tab settingsTab;
@FXML @FXML
private Tab functionListTab;
@FXML
private TableView<HistoryModel> historyTable; private TableView<HistoryModel> historyTable;
@FXML @FXML
private TableColumn<HistoryModel, String> inputColumn; private TableColumn<HistoryModel, String> inputColumn;
@@ -93,6 +102,10 @@ public class AbacusController implements PluginListener {
private ListView<ToggleablePlugin> enabledPluginView; private ListView<ToggleablePlugin> enabledPluginView;
@FXML @FXML
private TextField computationLimitField; private TextField computationLimitField;
@FXML
private ListView<Documentation> functionListView;
@FXML
private TextField functionListSearchField;
/** /**
* The list of history entries, created by the users. * The list of history entries, created by the users.
@@ -110,6 +123,14 @@ public class AbacusController implements PluginListener {
* and, when reloaded, get added to the plugin manager's black list. * and, when reloaded, get added to the plugin manager's black list.
*/ */
private ObservableList<ToggleablePlugin> enabledPlugins; private ObservableList<ToggleablePlugin> enabledPlugins;
/**
* The list of functions that are registered in the calculator.
*/
private ObservableList<Documentation> functionList;
/**
* The filtered list displayed to the user.
*/
private FilteredList<Documentation> functionFilter;
/** /**
* The abacus instance used for changing the plugin configuration. * The abacus instance used for changing the plugin configuration.
@@ -201,7 +222,7 @@ public class AbacusController implements PluginListener {
Callback<TableColumn<HistoryModel, String>, TableCell<HistoryModel, String>> cellFactory = Callback<TableColumn<HistoryModel, String>, TableCell<HistoryModel, String>> cellFactory =
param -> new CopyableCell<>(); param -> new CopyableCell<>();
Callback<ListView<ToggleablePlugin>, ListCell<ToggleablePlugin>> pluginCellFactory = Callback<ListView<ToggleablePlugin>, ListCell<ToggleablePlugin>> pluginCellFactory =
param -> new CheckBoxListCell<>(ToggleablePlugin::enabledProperty, new StringConverter<ToggleablePlugin>() { param -> new CheckBoxListCell<>(ToggleablePlugin::getEnabledProperty, new StringConverter<ToggleablePlugin>() {
@Override @Override
public String toString(ToggleablePlugin object) { public String toString(ToggleablePlugin object) {
return object.getClassName().substring(object.getClassName().lastIndexOf('.') + 1); return object.getClassName().substring(object.getClassName().lastIndexOf('.') + 1);
@@ -209,10 +230,15 @@ public class AbacusController implements PluginListener {
@Override @Override
public ToggleablePlugin fromString(String string) { public ToggleablePlugin fromString(String string) {
return new ToggleablePlugin(true, string); return new ToggleablePlugin(string, true);
} }
}); });
functionList = FXCollections.observableArrayList();
functionFilter = new FilteredList<>(functionList, (s) -> true);
functionListView.setItems(functionFilter);
functionListSearchField.textProperty().addListener((observable, oldValue, newValue) ->
functionFilter.setPredicate((newValue.length() == 0) ? ((s) -> true) : ((s) -> s.matches(newValue))));
functionListView.setCellFactory(param -> new DocumentationCell());
historyData = FXCollections.observableArrayList(); historyData = FXCollections.observableArrayList();
historyTable.setItems(historyData); historyTable.setItems(historyData);
numberImplementationOptions = FXCollections.observableArrayList(); numberImplementationOptions = FXCollections.observableArrayList();
@@ -223,11 +249,11 @@ public class AbacusController implements PluginListener {
enabledPluginView.setItems(enabledPlugins); enabledPluginView.setItems(enabledPlugins);
enabledPluginView.setCellFactory(pluginCellFactory); enabledPluginView.setCellFactory(pluginCellFactory);
inputColumn.setCellFactory(cellFactory); inputColumn.setCellFactory(cellFactory);
inputColumn.setCellValueFactory(cell -> cell.getValue().inputProperty()); inputColumn.setCellValueFactory(cell -> cell.getValue().getInputProperty());
parsedColumn.setCellFactory(cellFactory); parsedColumn.setCellFactory(cellFactory);
parsedColumn.setCellValueFactory(cell -> cell.getValue().parsedProperty()); parsedColumn.setCellValueFactory(cell -> cell.getValue().getParsedProperty());
outputColumn.setCellFactory(cellFactory); outputColumn.setCellFactory(cellFactory);
outputColumn.setCellValueFactory(cell -> cell.getValue().outputProperty()); outputColumn.setCellValueFactory(cell -> cell.getValue().getOutputProperty());
coreTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { coreTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (oldValue.equals(settingsTab)) alertIfApplyNeeded(true); if (oldValue.equals(settingsTab)) alertIfApplyNeeded(true);
}); });
@@ -235,13 +261,7 @@ public class AbacusController implements PluginListener {
abacus = new Abacus(new Configuration(CONFIG_FILE)); abacus = new Abacus(new Configuration(CONFIG_FILE));
PluginManager abacusPluginManager = abacus.getPluginManager(); PluginManager abacusPluginManager = abacus.getPluginManager();
abacusPluginManager.addListener(this); abacusPluginManager.addListener(this);
abacusPluginManager.addInstantiated(new StandardPlugin(abacus.getPluginManager())); performScan();
try {
ClassFinder.loadJars("plugins").forEach(abacusPluginManager::addClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
abacusPluginManager.reload();
computationLimitField.setText(Double.toString(abacus.getConfiguration().getComputationDelay())); computationLimitField.setText(Double.toString(abacus.getConfiguration().getComputationDelay()));
computationLimitField.textProperty().addListener((observable, oldValue, newValue) -> { computationLimitField.textProperty().addListener((observable, oldValue, newValue) -> {
@@ -291,6 +311,19 @@ public class AbacusController implements PluginListener {
reloadAlertShown = false; reloadAlertShown = false;
} }
@FXML
public void performScan(){
PluginManager abacusPluginManager = abacus.getPluginManager();
abacusPluginManager.removeAll();
abacusPluginManager.addInstantiated(new StandardPlugin(abacus.getPluginManager()));
try {
ClassFinder.loadJars("plugins").forEach(abacusPluginManager::addClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
abacusPluginManager.reload();
}
@FXML @FXML
public void performReload() { public void performReload() {
alertIfApplyNeeded(true); alertIfApplyNeeded(true);
@@ -323,14 +356,19 @@ public class AbacusController implements PluginListener {
numberImplementationBox.getSelectionModel().select(toSelect); numberImplementationBox.getSelectionModel().select(toSelect);
for (Class<?> pluginClass : abacus.getPluginManager().getLoadedPluginClasses()) { for (Class<?> pluginClass : abacus.getPluginManager().getLoadedPluginClasses()) {
String fullName = pluginClass.getName(); String fullName = pluginClass.getName();
ToggleablePlugin plugin = new ToggleablePlugin(!disabledPlugins.contains(fullName), fullName); ToggleablePlugin plugin = new ToggleablePlugin(fullName, !disabledPlugins.contains(fullName));
plugin.enabledProperty().addListener(e -> changesMade = true); plugin.getEnabledProperty().addListener(e -> changesMade = true);
enabledPlugins.add(plugin); enabledPlugins.add(plugin);
} }
PluginManager pluginManager = abacus.getPluginManager();
functionList.addAll(manager.getAllFunctions().stream().map(name -> pluginManager.documentationFor(name, DocumentationType.FUNCTION))
.collect(Collectors.toCollection(ArrayList::new)));
functionList.sort(Comparator.comparing(Documentation::getCodeName));
} }
@Override @Override
public void onUnload(PluginManager manager) { public void onUnload(PluginManager manager) {
functionList.clear();
enabledPlugins.clear(); enabledPlugins.clear();
numberImplementationOptions.clear(); numberImplementationOptions.clear();
} }

View File

@@ -0,0 +1,59 @@
package org.nwapw.abacus.fx;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import org.nwapw.abacus.function.Documentation;
public class DocumentationCell extends ListCell<Documentation> {
private Label codeNameLabel;
private Label nameLabel;
private Label description;
private Label longDescription;
private TitledPane titledPane;
public DocumentationCell(){
VBox vbox = new VBox();
vbox.setSpacing(10);
titledPane = new TitledPane();
codeNameLabel = new Label();
nameLabel = new Label();
description = new Label();
longDescription = new Label();
codeNameLabel.setWrapText(true);
nameLabel.setWrapText(true);
description.setWrapText(true);
longDescription.setWrapText(true);
vbox.getChildren().add(codeNameLabel);
vbox.getChildren().add(nameLabel);
vbox.getChildren().add(description);
vbox.getChildren().add(longDescription);
titledPane.textProperty().bindBidirectional(codeNameLabel.textProperty());
titledPane.setContent(vbox);
titledPane.setExpanded(false);
titledPane.prefWidthProperty().bind(widthProperty().subtract(32));
visibleProperty().addListener((a, b, c) -> titledPane.setExpanded(false));
}
@Override
protected void updateItem(Documentation item, boolean empty) {
super.updateItem(item, empty);
if(empty){
codeNameLabel.setText("");
nameLabel.setText("");
description.setText("");
longDescription.setText("");
setGraphic(null);
} else {
codeNameLabel.setText(item.getCodeName());
nameLabel.setText(item.getName());
description.setText(item.getDescription());
longDescription.setText(item.getLongDescription());
setGraphic(titledPane);
}
titledPane.setExpanded(false);
}
}

View File

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

View File

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

View File

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

View File

@@ -173,7 +173,7 @@ public abstract class NumberInterface {
/** /**
* Returns the least integer greater than or equal to the number. * Returns the least integer greater than or equal to the number.
* *
* @return the least integer >= the number, if int can hold the value. * @return the least integer greater or equal to the number, if int can hold the value.
*/ */
protected abstract NumberInterface ceilingInternal(); protected abstract NumberInterface ceilingInternal();
@@ -182,7 +182,7 @@ public abstract class NumberInterface {
* Also, checks if the thread has been interrupted, and if so, throws * Also, checks if the thread has been interrupted, and if so, throws
* an exception. * an exception.
* *
* @return the least integer bigger or equal to the number, if int can hold the value. * @return the least integer bigger or equal to the number.
*/ */
public final NumberInterface ceiling(){ public final NumberInterface ceiling(){
checkInterrupted(); checkInterrupted();
@@ -192,7 +192,7 @@ public abstract class NumberInterface {
/** /**
* Return the greatest integer less than or equal to the number. * Return the greatest integer less than or equal to the number.
* *
* @return the greatest integer smaller or equal the number, if int can hold the value. * @return the greatest integer smaller or equal the number.
*/ */
protected abstract NumberInterface floorInternal(); protected abstract NumberInterface floorInternal();
@@ -201,7 +201,7 @@ public abstract class NumberInterface {
* Also, checks if the thread has been interrupted, and if so, throws * Also, checks if the thread has been interrupted, and if so, throws
* an exception. * an exception.
* *
* @return the greatest int >= the number, if int can hold the value. * @return the greatest int smaller than or equal to the number.
*/ */
public final NumberInterface floor(){ public final NumberInterface floor(){
checkInterrupted(); checkInterrupted();
@@ -216,7 +216,7 @@ public abstract class NumberInterface {
protected abstract NumberInterface fractionalPartInternal(); protected abstract NumberInterface fractionalPartInternal();
/** /**
* Returns the fractional part of the number. * Returns the fractional part of the number, specifically x - floor(x).
* Also, checks if the thread has been interrupted, * Also, checks if the thread has been interrupted,
* and if so, throws an exception. * and if so, throws an exception.
* @return the fractional part of the number. * @return the fractional part of the number.
@@ -240,6 +240,7 @@ public abstract class NumberInterface {
* @param toClass the class to promote to. * @param toClass the class to promote to.
* @return the resulting new instance. * @return the resulting new instance.
*/ */
@Deprecated
protected abstract NumberInterface promoteToInternal(Class<? extends NumberInterface> toClass); protected abstract NumberInterface promoteToInternal(Class<? extends NumberInterface> toClass);
/** /**
@@ -250,9 +251,17 @@ public abstract class NumberInterface {
* @param toClass the class to promote to. * @param toClass the class to promote to.
* @return the resulting new instance. * @return the resulting new instance.
*/ */
@Deprecated
public final NumberInterface promoteTo(Class<? extends NumberInterface> toClass) { public final NumberInterface promoteTo(Class<? extends NumberInterface> toClass) {
checkInterrupted(); checkInterrupted();
return promoteToInternal(toClass); return promoteToInternal(toClass);
} }
/**
* Returns the smallest error this instance can tolerate depending
* on its precision and value.
* @return the smallest error that should be permitted in calculations.
*/
public abstract NumberInterface getMaxError();
} }

View File

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

View File

@@ -14,7 +14,7 @@ public abstract class NumberImplementation {
/** /**
* The list of paths through which this implementation can be promoted. * The list of paths through which this implementation can be promoted.
*/ */
protected Map<Class<? extends NumberInterface>, Function<NumberInterface, NumberInterface>> promotionPaths; private Map<Class<? extends NumberInterface>, Function<NumberInterface, NumberInterface>> promotionPaths;
/** /**
* The implementation class for this implementation. * The implementation class for this implementation.
*/ */

View File

@@ -1,5 +1,7 @@
package org.nwapw.abacus.plugin; package org.nwapw.abacus.plugin;
import org.nwapw.abacus.function.Documentation;
import org.nwapw.abacus.function.DocumentationType;
import org.nwapw.abacus.function.Function; import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator; import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
@@ -17,18 +19,6 @@ import java.util.Set;
*/ */
public abstract class Plugin { public abstract class Plugin {
/**
* A hash map of functions mapped to their string names.
*/
private Map<String, Function> functions;
/**
* A hash map of operators mapped to their string names.
*/
private Map<String, Operator> operators;
/**
* The map of the number implementations this plugin provides.
*/
private Map<String, NumberImplementation> numberImplementations;
/** /**
* The plugin manager in which to search for functions * The plugin manager in which to search for functions
* not inside this package, * not inside this package,
@@ -49,69 +39,9 @@ public abstract class Plugin {
*/ */
public Plugin(PluginManager manager) { public Plugin(PluginManager manager) {
this.manager = manager; this.manager = manager;
functions = new HashMap<>();
operators = new HashMap<>();
numberImplementations = new HashMap<>();
enabled = false; enabled = false;
} }
/**
* Gets the list of functions provided by this plugin.
*
* @return the list of registered functions.
*/
public final Set<String> providedFunctions() {
return functions.keySet();
}
/**
* Gets the list of functions provided by this plugin.
*
* @return the list of registered functions.
*/
public final Set<String> providedOperators() {
return operators.keySet();
}
/**
* Gets the list of number implementations provided by this plugin.
*
* @return the list of registered number implementations.
*/
public final Set<String> providedNumberImplementations() {
return numberImplementations.keySet();
}
/**
* Gets a function under the given function name.
*
* @param functionName the name of the function to get
* @return the function, or null if this plugin doesn't provide it.
*/
public final Function getFunction(String functionName) {
return functions.get(functionName);
}
/**
* Gets an operator under the given operator name.
*
* @param operatorName the name of the operator to get.
* @return the operator, or null if this plugin doesn't provide it.
*/
public final Operator getOperator(String operatorName) {
return operators.get(operatorName);
}
/**
* Gets the number implementation 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.
*/
public final NumberImplementation getNumberImplementation(String name) {
return numberImplementations.get(name);
}
/** /**
* Enables the function, loading the necessary instances * Enables the function, loading the necessary instances
* of functions. * of functions.
@@ -129,8 +59,6 @@ public abstract class Plugin {
public final void disable() { public final void disable() {
if (!enabled) return; if (!enabled) return;
onDisable(); onDisable();
functions.clear();
operators.clear();
enabled = false; enabled = false;
} }
@@ -142,7 +70,7 @@ public abstract class Plugin {
* @param toRegister the function implementation. * @param toRegister the function implementation.
*/ */
protected final void registerFunction(String name, Function toRegister) { protected final void registerFunction(String name, Function toRegister) {
functions.put(name, toRegister); manager.registerFunction(name, toRegister);
} }
/** /**
@@ -154,7 +82,7 @@ public abstract class Plugin {
* @param operator the operator to register. * @param operator the operator to register.
*/ */
protected final void registerOperator(String name, Operator operator) { protected final void registerOperator(String name, Operator operator) {
operators.put(name, operator); manager.registerOperator(name, operator);
} }
/** /**
@@ -165,7 +93,16 @@ public abstract class Plugin {
* @param implementation the actual implementation class to register. * @param implementation the actual implementation class to register.
*/ */
protected final void registerNumberImplementation(String name, NumberImplementation implementation) { protected final void registerNumberImplementation(String name, NumberImplementation implementation) {
numberImplementations.put(name, implementation); manager.registerNumberImplementation(name, implementation);
}
/**
* To be used in load(). Registers a documentation instance
* used to explain some element of the plugin to the user.
* @param documentation the documentation instance.
*/
protected final void registerDocumentation(Documentation documentation){
manager.registerDocumentation(documentation);
} }
/** /**
@@ -204,6 +141,17 @@ public abstract class Plugin {
return manager.numberImplementationFor(name); return manager.numberImplementationFor(name);
} }
/**
* Searches the PluginManager for the given documentation name and type.
*
* @param name the name for which to search.
* @param type the type of documentation to search for.
* @return the found documentation, or null if none was found.
*/
protected final Documentation documentationFor(String name, DocumentationType type){
return manager.documentationFor(name, type);
}
/** /**
* Searches the plugin manager for a Pi value for the given number implementation. * 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 * This is done so that number implementations with various degrees of precision
@@ -213,7 +161,7 @@ public abstract class Plugin {
* @param forClass the class to which to find the pi instance. * @param forClass the class to which to find the pi instance.
* @return the pi value for the given class. * @return the pi value for the given class.
*/ */
protected final NumberInterface getPi(Class<? extends NumberInterface> forClass) { protected final NumberInterface piFor(Class<? extends NumberInterface> forClass) {
return manager.piFor(forClass); return manager.piFor(forClass);
} }

View File

@@ -1,6 +1,8 @@
package org.nwapw.abacus.plugin; package org.nwapw.abacus.plugin;
import org.nwapw.abacus.Abacus; import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Documentation;
import org.nwapw.abacus.function.DocumentationType;
import org.nwapw.abacus.function.Function; import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator; import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
@@ -23,20 +25,21 @@ public class PluginManager {
*/ */
private Set<Plugin> plugins; private Set<Plugin> plugins;
/** /**
* List of functions that have been cached, * The map of functions registered by the plugins.
* that is, found in a plugin and returned.
*/ */
private Map<String, Function> cachedFunctions; private Map<String, Function> registeredFunctions;
/** /**
* List of operators that have been cached, * The map of operators registered by the plugins
* that is, found in a plugin and returned.
*/ */
private Map<String, Operator> cachedOperators; private Map<String, Operator> registeredOperators;
/** /**
* The list of number implementations that have * The map of number implementations registered by the plugins.
* been cached, that is, found in a plugin and returned.
*/ */
private Map<String, NumberImplementation> cachedNumberImplementations; private Map<String, NumberImplementation> registeredNumberImplementations;
/**
* The map of documentation for functions registered by the plugins.
*/
private Set<Documentation> registeredDocumentation;
/** /**
* The list of number implementations that have been * The list of number implementations that have been
* found by their implementation class. * found by their implementation class.
@@ -46,18 +49,6 @@ public class PluginManager {
* The pi values for each implementation class that have already been computer. * The pi values for each implementation class that have already been computer.
*/ */
private Map<Class<? extends NumberInterface>, NumberInterface> cachedPi; private Map<Class<? extends NumberInterface>, NumberInterface> cachedPi;
/**
* List of all functions loaded by the plugins.
*/
private Set<String> allFunctions;
/**
* List of all operators loaded by the plugins.
*/
private Set<String> allOperators;
/**
* List of all the number implementations loaded by the plugins.
*/
private Set<String> allNumberImplementations;
/** /**
* The list of plugin listeners attached to this instance. * The list of plugin listeners attached to this instance.
*/ */
@@ -77,79 +68,97 @@ public class PluginManager {
this.abacus = abacus; this.abacus = abacus;
loadedPluginClasses = new HashSet<>(); loadedPluginClasses = new HashSet<>();
plugins = new HashSet<>(); plugins = new HashSet<>();
cachedFunctions = new HashMap<>(); registeredFunctions = new HashMap<>();
cachedOperators = new HashMap<>(); registeredOperators = new HashMap<>();
cachedNumberImplementations = new HashMap<>(); registeredNumberImplementations = new HashMap<>();
registeredDocumentation = new HashSet<>();
cachedInterfaceImplementations = new HashMap<>(); cachedInterfaceImplementations = new HashMap<>();
cachedPi = new HashMap<>(); cachedPi = new HashMap<>();
allFunctions = new HashSet<>();
allOperators = new HashSet<>();
allNumberImplementations = new HashSet<>();
listeners = new HashSet<>(); listeners = new HashSet<>();
} }
/** /**
* Searches the plugin list for a certain value, retrieving the Plugin's * Registers a function under the given name.
* list of items of the type using the setFunction and getting the value * @param name the name of the function.
* of it is available via getFunction. If the value is contained * @param function the function to register.
* in the cache, it returns the cached value instead.
*
* @param plugins the plugin list to search.
* @param cache the cache to use
* @param setFunction the function to retrieve a set of available T's from the plugin
* @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, public void registerFunction(String name, Function function){
java.util.function.Function<Plugin, Set<K>> setFunction, registeredFunctions.put(name, function);
java.util.function.BiFunction<Plugin, K, T> getFunction, }
K name) {
if (cache.containsKey(name)) return cache.get(name);
T loadedValue = null; /**
for (Plugin plugin : plugins) { * Registers an operator under the given name.
if (setFunction.apply(plugin).contains(name)) { * @param name the name of the operator.
loadedValue = getFunction.apply(plugin, name); * @param operator the operator to register.
*/
public void registerOperator(String name, Operator operator){
registeredOperators.put(name, operator);
}
/**
* Registers a number implementation under the given name.
* @param name the name of the number implementation.
* @param implementation the number implementation to register.
*/
public void registerNumberImplementation(String name, NumberImplementation implementation){
registeredNumberImplementations.put(name, implementation);
}
/**
* Registers the given documentation with the plugin manager,
* making it accessible to the plugin manager etc.
* @param documentation the documentation to register.
*/
public void registerDocumentation(Documentation documentation){
registeredDocumentation.add(documentation);
}
/**
* Gets the function registered under the given name.
* @param name the name of the function.
* @return the function, or null if it was not found.
*/
public Function functionFor(String name){
return registeredFunctions.get(name);
}
/**
* Gets the operator registered under the given name.
* @param name the name of the operator.
* @return the operator, or null if it was not found.
*/
public Operator operatorFor(String name){
return registeredOperators.get(name);
}
/**
* Gets the number implementation registered under the given name.
* @param name the name of the number implementation.
* @return the number implementation, or null if it was not found.
*/
public NumberImplementation numberImplementationFor(String name){
return registeredNumberImplementations.get(name);
}
/**
* Gets the documentation for the given entity of the given type.
* @param name the name of the entity to search for.
* @param type the type that this entity is, to filter out similarly named documentation.
* @return the documentation object.
*/
public Documentation documentationFor(String name, DocumentationType type){
Documentation toReturn = null;
for(Documentation entry : registeredDocumentation){
if(entry.getCodeName().equals(name) && entry.getType() == type) {
toReturn = entry;
break; break;
} }
} }
if(toReturn == null){
cache.put(name, loadedValue); toReturn = new Documentation(name, "", "", "", type);
return loadedValue; registerDocumentation(toReturn);
} }
return toReturn;
/**
* Gets a function under the given name.
*
* @param name the name of the function
* @return the function under the given name.
*/
public Function functionFor(String name) {
return searchCached(plugins, cachedFunctions, Plugin::providedFunctions, Plugin::getFunction, name);
}
/**
* Gets an operator under the given name.
*
* @param name the name of the operator.
* @return the operator under the given name.
*/
public Operator operatorFor(String name) {
return searchCached(plugins, cachedOperators, Plugin::providedOperators, Plugin::getOperator, name);
}
/**
* Gets the number implementation under the given name.
*
* @param name the name of the implementation.
* @return the implementation.
*/
public NumberImplementation numberImplementationFor(String name) {
return searchCached(plugins, cachedNumberImplementations, Plugin::providedNumberImplementations,
Plugin::getNumberImplementation, name);
} }
/** /**
@@ -161,14 +170,11 @@ public class PluginManager {
public NumberImplementation interfaceImplementationFor(Class<? extends NumberInterface> name) { public NumberImplementation interfaceImplementationFor(Class<? extends NumberInterface> name) {
if (cachedInterfaceImplementations.containsKey(name)) return cachedInterfaceImplementations.get(name); if (cachedInterfaceImplementations.containsKey(name)) return cachedInterfaceImplementations.get(name);
NumberImplementation toReturn = null; NumberImplementation toReturn = null;
outside: for(String key : registeredNumberImplementations.keySet()){
for (Plugin plugin : plugins) { NumberImplementation implementation = registeredNumberImplementations.get(key);
for (String implementationName : plugin.providedNumberImplementations()) { if(implementation.getImplementation() == name) {
NumberImplementation implementation = plugin.getNumberImplementation(implementationName); toReturn = implementation;
if (implementation.getImplementation().equals(name)) { break;
toReturn = implementation;
break outside;
}
} }
} }
cachedInterfaceImplementations.put(name, toReturn); cachedInterfaceImplementations.put(name, toReturn);
@@ -218,6 +224,24 @@ public class PluginManager {
} }
} }
/**
* Removes the plugin with the given class from the manager.
* @param toRemove the plugin to remove.
*/
public void removeClass(Class<? extends Plugin> toRemove){
if(!loadedPluginClasses.contains(toRemove)) return;
plugins.removeIf(plugin -> plugin.getClass() == toRemove);
loadedPluginClasses.remove(toRemove);
}
/**
* Removes all plugins from this plugin manager.
*/
public void removeAll(){
loadedPluginClasses.clear();
plugins.clear();
}
/** /**
* Loads all the plugins in the PluginManager. * Loads all the plugins in the PluginManager.
*/ */
@@ -227,12 +251,6 @@ public class PluginManager {
if (disabledPlugins.contains(plugin.getClass().getName())) continue; if (disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.enable(); plugin.enable();
} }
for (Plugin plugin : plugins) {
if (disabledPlugins.contains(plugin.getClass().getName())) continue;
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumberImplementations.addAll(plugin.providedNumberImplementations());
}
listeners.forEach(e -> e.onLoad(this)); listeners.forEach(e -> e.onLoad(this));
} }
@@ -246,14 +264,12 @@ public class PluginManager {
if (disabledPlugins.contains(plugin.getClass().getName())) continue; if (disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.disable(); plugin.disable();
} }
cachedFunctions.clear(); registeredFunctions.clear();
cachedOperators.clear(); registeredOperators.clear();
cachedNumberImplementations.clear(); registeredNumberImplementations.clear();
registeredDocumentation.clear();
cachedInterfaceImplementations.clear(); cachedInterfaceImplementations.clear();
cachedPi.clear(); cachedPi.clear();
allFunctions.clear();
allOperators.clear();
allNumberImplementations.clear();
listeners.forEach(e -> e.onUnload(this)); listeners.forEach(e -> e.onUnload(this));
} }
@@ -271,7 +287,7 @@ public class PluginManager {
* @return the set of all functions that were loaded. * @return the set of all functions that were loaded.
*/ */
public Set<String> getAllFunctions() { public Set<String> getAllFunctions() {
return allFunctions; return registeredFunctions.keySet();
} }
/** /**
@@ -280,7 +296,7 @@ public class PluginManager {
* @return the set of all operators that were loaded. * @return the set of all operators that were loaded.
*/ */
public Set<String> getAllOperators() { public Set<String> getAllOperators() {
return allOperators; return registeredOperators.keySet();
} }
/** /**
@@ -289,7 +305,7 @@ public class PluginManager {
* @return the set of all implementations that were loaded. * @return the set of all implementations that were loaded.
*/ */
public Set<String> getAllNumberImplementations() { public Set<String> getAllNumberImplementations() {
return allNumberImplementations; return registeredNumberImplementations.keySet();
} }
/** /**

View File

@@ -1,15 +1,19 @@
package org.nwapw.abacus.plugin; package org.nwapw.abacus.plugin;
import org.nwapw.abacus.function.Function; import org.nwapw.abacus.function.*;
import org.nwapw.abacus.function.Operator; import org.nwapw.abacus.lexing.pattern.Match;
import org.nwapw.abacus.function.OperatorAssociativity;
import org.nwapw.abacus.function.OperatorType;
import org.nwapw.abacus.number.NaiveNumber; import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.PreciseNumber; import org.nwapw.abacus.number.PreciseNumber;
import org.nwapw.abacus.parsing.Parser;
import org.nwapw.abacus.parsing.ShuntingYardParser;
import org.nwapw.abacus.tree.TokenType;
import org.nwapw.abacus.tree.TreeNode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.function.BiFunction; import java.util.function.BiFunction;
/** /**
@@ -18,6 +22,11 @@ import java.util.function.BiFunction;
*/ */
public class StandardPlugin extends Plugin { public class StandardPlugin extends Plugin {
/**
* Stores objects of NumberInterface with integer values for reuse.
*/
private final static HashMap<Class<? extends NumberInterface>, HashMap<Integer, NumberInterface>> integerValues = new HashMap<>();
/** /**
* The addition operator, + * The addition operator, +
*/ */
@@ -89,7 +98,7 @@ public class StandardPlugin extends Plugin {
public static final Operator OP_DIVIDE = new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 1, new Function() { public static final Operator OP_DIVIDE = new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 1, new Function() {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2 && params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) != 0; return params.length == 2 && params[1].compareTo(fromInt(params[0].getClass(), 0)) != 0;
} }
@Override @Override
@@ -105,19 +114,20 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { 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].fractionalPart().compareTo(fromInt(params[0].getClass(), 0)) == 0
&& params[0].signum() >= 0; && params[0].signum() >= 0;
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
if (params[0].signum() == 0) { if (params[0].signum() == 0) {
return (new NaiveNumber(1)).promoteTo(params[0].getClass()); return fromInt(params[0].getClass(), 1);
} }
NumberInterface one = fromInt(params[0].getClass(), 1);
NumberInterface factorial = params[0]; NumberInterface factorial = params[0];
NumberInterface multiplier = params[0]; NumberInterface multiplier = params[0];
//It is necessary to later prevent calls of factorial on anything but non-negative integers. //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 ((multiplier = multiplier.subtract(one)).signum() == 1) {
factorial = factorial.multiply(multiplier); factorial = factorial.multiply(multiplier);
} }
return factorial; return factorial;
@@ -128,6 +138,51 @@ public class StandardPlugin extends Plugin {
}*/ }*/
} }
}); });
/**
* The permutation operator.
*/
public static final Operator OP_NPR = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 0, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2 && params[0].fractionalPart().signum() == 0
&& params[1].fractionalPart().signum() == 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(params[0].compareTo(params[1]) < 0 ||
params[0].signum() < 0 ||
(params[0].signum() == 0 && params[1].signum() != 0)) return fromInt(params[0].getClass(), 0);
NumberInterface total = fromInt(params[0].getClass(), 1);
NumberInterface multiplyBy = params[0];
NumberInterface remainingMultiplications = params[1];
NumberInterface halfway = params[0].divide(fromInt(params[0].getClass(), 2));
if(remainingMultiplications.compareTo(halfway) > 0){
remainingMultiplications = params[0].subtract(remainingMultiplications);
}
while(remainingMultiplications.signum() > 0){
total = total.multiply(multiplyBy);
remainingMultiplications = remainingMultiplications.subtract(fromInt(params[0].getClass(), 1));
multiplyBy = multiplyBy.subtract(fromInt(params[0].getClass(), 1));
}
return total;
}
});
/**
* The combination operator.
*/
public static final Operator OP_NCR = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 0, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2 && params[0].fractionalPart().signum() == 0
&& params[1].fractionalPart().signum() == 0;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return OP_NPR.getFunction().apply(params).divide(OP_FACTORIAL.getFunction().apply(params[1]));
}
});
/** /**
* The absolute value function, abs(-3) = 3 * The absolute value function, abs(-3) = 3
*/ */
@@ -139,7 +194,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass())); return params[0].multiply(fromInt(params[0].getClass(), params[0].signum()));
} }
}; };
/** /**
@@ -148,31 +203,32 @@ public class StandardPlugin extends Plugin {
public static final Function FUNCTION_LN = new Function() { public static final Function FUNCTION_LN = new Function() {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 && params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) > 0; return params.length == 1 && params[0].compareTo(fromInt(params[0].getClass(), 0)) > 0;
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface param = params[0]; NumberInterface param = params[0];
NumberInterface one = fromInt(param.getClass(), 1);
int powersOf2 = 0; int powersOf2 = 0;
while (FUNCTION_ABS.apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))).compareTo(new NaiveNumber(0.1).promoteTo(param.getClass())) >= 0) { while (FUNCTION_ABS.apply(param.subtract(one)).compareTo(new NaiveNumber(0.1).promoteTo(param.getClass())) >= 0) {
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() == 1) { if (param.subtract(one).signum() == 1) {
param = param.divide(new NaiveNumber(2).promoteTo(param.getClass())); param = param.divide(fromInt(param.getClass(), 2));
powersOf2++; powersOf2++;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) { if (param.subtract(one).signum() != 1) {
break; break;
//No infinite loop for you. //No infinite loop for you.
} }
} else { } else {
param = param.multiply(new NaiveNumber(2).promoteTo(param.getClass())); param = param.multiply(fromInt(param.getClass(), 2));
powersOf2--; powersOf2--;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != -1) { if (param.subtract(one).signum() != -1) {
break; break;
//No infinite loop for you. //No infinite loop for you.
} }
} }
} }
return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClass())).add(getLogPartialSum(param)); return getLog2(param).multiply(fromInt(param.getClass(), powersOf2)).add(getLogPartialSum(param));
} }
/** /**
@@ -183,14 +239,14 @@ public class StandardPlugin extends Plugin {
*/ */
private NumberInterface getLogPartialSum(NumberInterface x) { private NumberInterface getLogPartialSum(NumberInterface x) {
NumberInterface maxError = getMaxError(x); NumberInterface maxError = x.getMaxError();
x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClass())); //Terms used are for log(x+1). x = x.subtract(fromInt(x.getClass(), 1)); //Terms used are for log(x+1).
NumberInterface currentNumerator = x, currentTerm = x, sum = x; NumberInterface currentNumerator = x, currentTerm = x, sum = x;
int n = 1; int n = 1;
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) { while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) {
n++; n++;
currentNumerator = currentNumerator.multiply(x).negate(); currentNumerator = currentNumerator.multiply(x).negate();
currentTerm = currentNumerator.divide(new NaiveNumber(n).promoteTo(x.getClass())); currentTerm = currentNumerator.divide(fromInt(x.getClass(), n));
sum = sum.add(currentTerm); sum = sum.add(currentTerm);
} }
return sum; return sum;
@@ -202,19 +258,20 @@ public class StandardPlugin extends Plugin {
* @return the value of log(2) with the appropriate precision. * @return the value of log(2) with the appropriate precision.
*/ */
private NumberInterface getLog2(NumberInterface number) { private NumberInterface getLog2(NumberInterface number) {
NumberInterface maxError = getMaxError(number); NumberInterface maxError = number.getMaxError();
//NumberInterface errorBound = (new NaiveNumber(1)).promoteTo(number.getClass()); //NumberInterface errorBound = fromInt(number.getClass(), 1);
//We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n) //We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n)
//In the following, a=1/3^n, b=1/4^n, c = 1/n. //In the following, a=1/3^n, b=1/4^n, c = 1/n.
//a is also an error bound. //a is also an error bound.
NumberInterface a = (new NaiveNumber(1)).promoteTo(number.getClass()), b = a, c = a; NumberInterface a = fromInt(number.getClass(), 1), b = a, c = a;
NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClass()); NumberInterface sum = fromInt(number.getClass(), 0);
NumberInterface one = fromInt(number.getClass(), 1);
int n = 0; int n = 0;
while (a.compareTo(maxError) >= 1) { while (a.compareTo(maxError) >= 1) {
n++; n++;
a = a.divide((new NaiveNumber(3)).promoteTo(number.getClass())); a = a.divide(fromInt(number.getClass(), 3));
b = b.divide((new NaiveNumber(4)).promoteTo(number.getClass())); b = b.divide(fromInt(number.getClass(), 4));
c = NaiveNumber.ONE.promoteTo(number.getClass()).divide((new NaiveNumber(n)).promoteTo(number.getClass())); c = one.divide(fromInt(number.getClass(), n));
sum = sum.add(a.add(b).multiply(c)); sum = sum.add(a.add(b).multiply(c));
} }
return sum; return sum;
@@ -234,6 +291,20 @@ public class StandardPlugin extends Plugin {
return OP_CARET.getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClass()))); return OP_CARET.getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClass())));
} }
}; };
/**
* Gets a random number smaller or equal to the given number's integer value.
*/
public static final Function FUNCTION_RAND_INT = new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return fromInt(params[0].getClass(), (int) Math.round(Math.random() * params[0].floor().intValue()));
}
};
/** /**
* The implementation for double-based naive numbers. * The implementation for double-based naive numbers.
*/ */
@@ -273,10 +344,10 @@ public class StandardPlugin extends Plugin {
.negate(); .negate();
for (int i = 0; i < termsNeeded; i++) { for (int i = 0; i < termsNeeded; i++) {
M = M M = M
.multiply(new NaiveNumber(12 * i + 2).promoteTo(PreciseNumber.class)) .multiply(new PreciseNumber((12 * i + 2) + ""))
.multiply(new NaiveNumber(12 * i + 6).promoteTo(PreciseNumber.class)) .multiply(new PreciseNumber((12 * i + 6) + ""))
.multiply(new NaiveNumber(12 * i + 10).promoteTo(PreciseNumber.class)) .multiply(new PreciseNumber((12 * i + 10) + ""))
.divide(new NaiveNumber(Math.pow(i + 1, 3)).promoteTo(PreciseNumber.class)); .divide(new PreciseNumber(Math.pow(i + 1, 3) + ""));
L = L.add(lSummand); L = L.add(lSummand);
X = X.multiply(xMultiplier); X = X.multiply(xMultiplier);
sum = sum.add(M.multiply(L).divide(X)); sum = sum.add(M.multiply(L).divide(X));
@@ -296,28 +367,23 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface maxError = getMaxError(params[0]); NumberInterface maxError = params[0].getMaxError();
int n = 0; int n = 0;
if (params[0].signum() <= 0) { if (params[0].signum() < 0) {
NumberInterface currentTerm = NaiveNumber.ONE.promoteTo(params[0].getClass()), sum = currentTerm; NumberInterface[] negatedParams = {params[0].negate()};
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) { return fromInt(params[0].getClass(), 1).divide(applyInternal(negatedParams));
n++;
currentTerm = currentTerm.multiply(params[0]).divide((new NaiveNumber(n)).promoteTo(params[0].getClass()));
sum = sum.add(currentTerm);
}
return sum;
} else { } else {
//We need n such that x^(n+1) * 3^ceil(x) <= maxError * (n+1)!. //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. //right and left refer to lhs and rhs in the above inequality.
NumberInterface sum = NaiveNumber.ONE.promoteTo(params[0].getClass()); NumberInterface sum = fromInt(params[0].getClass(), 1);
NumberInterface nextNumerator = params[0]; NumberInterface nextNumerator = params[0];
NumberInterface left = params[0].multiply((new NaiveNumber(3)).promoteTo(params[0].getClass()).intPow(params[0].ceiling().intValue())), right = maxError; NumberInterface left = params[0].multiply(fromInt(params[0].getClass(), 3).intPow(params[0].ceiling().intValue())), right = maxError;
do { do {
sum = sum.add(nextNumerator.divide(factorial(params[0].getClass(), n + 1))); sum = sum.add(nextNumerator.divide(factorial(params[0].getClass(), n + 1)));
n++; n++;
nextNumerator = nextNumerator.multiply(params[0]); nextNumerator = nextNumerator.multiply(params[0]);
left = left.multiply(params[0]); left = left.multiply(params[0]);
NumberInterface nextN = (new NaiveNumber(n + 1)).promoteTo(params[0].getClass()); NumberInterface nextN = fromInt(params[0].getClass(), n + 1);
right = right.multiply(nextN); right = right.multiply(nextN);
//System.out.println(left + ", " + right); //System.out.println(left + ", " + right);
} }
@@ -333,17 +399,27 @@ public class StandardPlugin extends Plugin {
public static final Operator OP_CARET = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 2, new Function() { public static final Operator OP_CARET = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 2, new Function() {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
NumberInterface zero = fromInt(params[0].getClass(), 0);
return params.length == 2 return params.length == 2
&& !(params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0 && !(params[0].compareTo(zero) == 0
&& params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) == 0); && params[1].compareTo(zero) == 0)
&& !(params[0].signum() == -1 && params[1].fractionalPart().compareTo(zero) != 0);
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
if (params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0) NumberInterface zero = fromInt(params[0].getClass(), 0);
return NaiveNumber.ZERO.promoteTo(params[0].getClass()); if (params[0].compareTo(zero) == 0)
else if (params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0) return zero;
return NaiveNumber.ONE.promoteTo(params[1].getClass()); else if (params[1].compareTo(zero) == 0)
return fromInt(params[0].getClass(), 1);
//Detect integer bases:
if(params[0].fractionalPart().compareTo(fromInt(params[0].getClass(), 0)) == 0
&& FUNCTION_ABS.apply(params[1]).compareTo(fromInt(params[0].getClass(), Integer.MAX_VALUE)) < 0
&& FUNCTION_ABS.apply(params[1]).compareTo(fromInt(params[1].getClass(), 1)) >= 0){
NumberInterface[] newParams = {params[0], params[1].fractionalPart()};
return params[0].intPow(params[1].floor().intValue()).multiply(applyInternal(newParams));
}
return FUNCTION_EXP.apply(FUNCTION_LN.apply(FUNCTION_ABS.apply(params[0])).multiply(params[1])); return FUNCTION_EXP.apply(FUNCTION_LN.apply(FUNCTION_ABS.apply(params[0])).multiply(params[1]));
} }
}); });
@@ -358,13 +434,13 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface pi = getPi(params[0].getClass()); NumberInterface pi = piFor(params[0].getClass());
NumberInterface twoPi = pi.multiply(new NaiveNumber(2).promoteTo(pi.getClass())); NumberInterface twoPi = pi.multiply(fromInt(pi.getClass(), 2));
NumberInterface theta = getSmallAngle(params[0], pi); NumberInterface theta = getSmallAngle(params[0], pi);
//System.out.println(theta); //System.out.println(theta);
if (theta.compareTo(pi.multiply(new NaiveNumber(1.5).promoteTo(twoPi.getClass()))) >= 0) { if (theta.compareTo(pi.multiply(new NaiveNumber(1.5).promoteTo(twoPi.getClass()))) >= 0) {
theta = theta.subtract(twoPi); theta = theta.subtract(twoPi);
} else if (theta.compareTo(pi.divide(new NaiveNumber(2).promoteTo(pi.getClass()))) > 0) { } else if (theta.compareTo(pi.divide(fromInt(pi.getClass(), 2))) > 0) {
theta = pi.subtract(theta); theta = pi.subtract(theta);
} }
//System.out.println(theta); //System.out.println(theta);
@@ -382,7 +458,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return functionSin.apply(getPi(params[0].getClass()).divide(new NaiveNumber(2).promoteTo(params[0].getClass())) return functionSin.apply(piFor(params[0].getClass()).divide(fromInt(params[0].getClass(), 2))
.subtract(params[0])); .subtract(params[0]));
} }
}; };
@@ -411,7 +487,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionCos.apply(params[0])); return fromInt(params[0].getClass(), 1).divide(functionCos.apply(params[0]));
} }
}; };
/** /**
@@ -425,7 +501,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionSin.apply(params[0])); return fromInt(params[0].getClass(), 1).divide(functionSin.apply(params[0]));
} }
}; };
/** /**
@@ -456,23 +532,13 @@ public class StandardPlugin extends Plugin {
* @return the value of the partial sum that has the same class as x. * @return the value of the partial sum that has the same class as x.
*/ */
private static NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n) { private static NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n) {
NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClass()); NumberInterface sum = fromInt(x.getClass(), 0);
for (int i = 0; i <= n; i++) { for (int i = 0; i <= n; i++) {
sum = sum.add(nthTermFunction.apply(i, x)); sum = sum.add(nthTermFunction.apply(i, x));
} }
return sum; return sum;
} }
/**
* Returns the maximum error based on the precision of the class of number.
*
* @param number Any instance of the NumberInterface in question (should return an appropriate precision).
* @return the maximum error.
*/
private static NumberInterface getMaxError(NumberInterface number) {
return (new NaiveNumber(10)).promoteTo(number.getClass()).intPow(-number.getMaxPrecision());
}
/** /**
* A factorial function that uses memoization for each number class; it efficiently * A factorial function that uses memoization for each number class; it efficiently
* computes factorials of non-negative integers. * computes factorials of non-negative integers.
@@ -484,13 +550,13 @@ public class StandardPlugin extends Plugin {
public static NumberInterface factorial(Class<? extends NumberInterface> numberClass, int n) { public static NumberInterface factorial(Class<? extends NumberInterface> numberClass, int n) {
if (!FACTORIAL_LISTS.containsKey(numberClass)) { if (!FACTORIAL_LISTS.containsKey(numberClass)) {
FACTORIAL_LISTS.put(numberClass, new ArrayList<>()); FACTORIAL_LISTS.put(numberClass, new ArrayList<>());
FACTORIAL_LISTS.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass)); FACTORIAL_LISTS.get(numberClass).add(fromInt(numberClass, 1));
FACTORIAL_LISTS.get(numberClass).add(NaiveNumber.ONE.promoteTo(numberClass)); FACTORIAL_LISTS.get(numberClass).add(fromInt(numberClass, 1));
} }
ArrayList<NumberInterface> list = FACTORIAL_LISTS.get(numberClass); ArrayList<NumberInterface> list = FACTORIAL_LISTS.get(numberClass);
if (n >= list.size()) { if (n >= list.size()) {
while (list.size() < n + 16) { while (list.size() < n + 16) {
list.add(list.get(list.size() - 1).multiply(new NaiveNumber(list.size()).promoteTo(numberClass))); list.add(list.get(list.size() - 1).multiply(fromInt(numberClass, list.size())));
} }
} }
return list.get(n); return list.get(n);
@@ -504,7 +570,7 @@ public class StandardPlugin extends Plugin {
*/ */
private static NumberInterface sinTaylor(NumberInterface x) { private static NumberInterface sinTaylor(NumberInterface x) {
NumberInterface power = x, multiplier = x.multiply(x).negate(), currentTerm = x, sum = x; NumberInterface power = x, multiplier = x.multiply(x).negate(), currentTerm = x, sum = x;
NumberInterface maxError = getMaxError(x); NumberInterface maxError = x.getMaxError();
int n = 1; int n = 1;
do { do {
n += 2; n += 2;
@@ -522,7 +588,7 @@ public class StandardPlugin extends Plugin {
* @return theta in [0, 2pi) that differs from phi by a multiple of 2pi. * @return theta in [0, 2pi) that differs from phi by a multiple of 2pi.
*/ */
private static NumberInterface getSmallAngle(NumberInterface phi, NumberInterface pi) { private static NumberInterface getSmallAngle(NumberInterface phi, NumberInterface pi) {
NumberInterface twoPi = pi.multiply(new NaiveNumber("2").promoteTo(phi.getClass())); NumberInterface twoPi = pi.multiply(fromInt(pi.getClass(), 2));
NumberInterface theta = FUNCTION_ABS.apply(phi).subtract(twoPi NumberInterface theta = FUNCTION_ABS.apply(phi).subtract(twoPi
.multiply(FUNCTION_ABS.apply(phi).divide(twoPi).floor())); //Now theta is in [0, 2pi). .multiply(FUNCTION_ABS.apply(phi).divide(twoPi).floor())); //Now theta is in [0, 2pi).
if (phi.signum() < 0) { if (phi.signum() < 0) {
@@ -531,6 +597,22 @@ public class StandardPlugin extends Plugin {
return theta; return theta;
} }
/**
* Returns a number of class numType with value n.
* @param numType class of number to return.
* @param n value of returned number.
* @return numClass instance with value n.
*/
private static NumberInterface fromInt(Class<? extends NumberInterface> numType, int n){
if(!integerValues.containsKey(numType)){
integerValues.put(numType, new HashMap<>());
}
if(!integerValues.get(numType).containsKey(n)){
integerValues.get(numType).put(n, new NaiveNumber(n).promoteTo(numType));
}
return integerValues.get(numType).get(n);
}
@Override @Override
public void onEnable() { public void onEnable() {
registerNumberImplementation("naive", IMPLEMENTATION_NAIVE); registerNumberImplementation("naive", IMPLEMENTATION_NAIVE);
@@ -544,6 +626,9 @@ public class StandardPlugin extends Plugin {
registerOperator("^", OP_CARET); registerOperator("^", OP_CARET);
registerOperator("!", OP_FACTORIAL); registerOperator("!", OP_FACTORIAL);
registerOperator("nPr", OP_NPR);
registerOperator("nCr", OP_NCR);
registerFunction("abs", FUNCTION_ABS); registerFunction("abs", FUNCTION_ABS);
registerFunction("exp", FUNCTION_EXP); registerFunction("exp", FUNCTION_EXP);
registerFunction("ln", FUNCTION_LN); registerFunction("ln", FUNCTION_LN);
@@ -554,6 +639,43 @@ public class StandardPlugin extends Plugin {
registerFunction("sec", functionSec); registerFunction("sec", functionSec);
registerFunction("csc", functionCsc); registerFunction("csc", functionCsc);
registerFunction("cot", functionCot); registerFunction("cot", functionCot);
registerFunction("random_int", FUNCTION_RAND_INT);
registerDocumentation(new Documentation("abs", "Absolute Value", "Finds the distance " +
"from zero of a number.", "Given a number, this function finds the distance form " +
"zero of a number, effectively turning negative numbers into positive ones.\n\n" +
"Example: abs(-2) -> 2", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("exp", "Exponentiate", "Brings e to the given power.",
"This function evaluates e to the power of the given value, and is the inverse " +
"of the natural logarithm.\n\n" +
"Example: exp(1) -> 2.718...", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("ln", "Natural Logarithm", "Gets the natural " +
"logarithm of the given value.", "The natural logarithm of a number is " +
"the power that e has to be brought to to be equal to the number.\n\n" +
"Example: ln(2.718) -> 1", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("sqrt", "Square Root", "Finds the square root " +
"of the number.", "A square root a of a number is defined such that a times a is equal " +
"to that number.\n\n" +
"Example: sqrt(4) -> 2", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("sin", "Sine", "Computes the sine of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("cos", "Cosine", "Computes the cosine of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("tan", "Tangent", "Computes the tangent of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("sec", "Secant", "Computes the secant of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("csc", "Cosecant", "Computes the cosecant of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("cot", "Cotangent", "Computes the cotangent of the given angle, " +
"in radians.", "", DocumentationType.FUNCTION));
registerDocumentation(new Documentation("random_int", "Random Integer", "Generates a random integer [0, n].",
"Generates a pseudorandom number using the standard JVM random mechanism, keeping it less than or " +
"equal to the given number.\n\n" +
"Example: random_int(5) -> 4\n" +
"random_int(5) -> 3\n" +
"random_int(5) -> 3\n", DocumentationType.FUNCTION));
} }
@Override @Override

View File

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

View File

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

View File

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

View File

@@ -1,19 +0,0 @@
package org.nwapw.abacus.tree;
/**
* Interface used to reduce a tree into a single value.
*
* @param <T> the value to reduce into.
*/
public interface Reducer<T> {
/**
* Reduces the given tree into a single value of type T.
*
* @param node the node being passed in to be reduced.
* @param children the already-reduced children of this node.
* @return the resulting value from the reduce.
*/
public T reduceNode(TreeNode node, Object... children);
}

View File

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

View File

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

View File

@@ -0,0 +1,26 @@
package org.nwapw.abacus.function
/**
* A data class used for storing information about a function.
*
* The Documentation class holds the information necessary to display the information
* about a function to the user.
*
* @param codeName the name of the function as it occurs in code.
* @param name the name of the function in English.
* @param description the short description of this function.
* @param longDescription the full description of this function.
* @param type the things this documentation maps to.
*/
data class Documentation(val codeName: String, val name: String,
val description: String, val longDescription: String,
val type: DocumentationType) {
fun matches(other: String): Boolean {
return codeName.toLowerCase().contains(other.toLowerCase()) ||
name.toLowerCase().contains(other.toLowerCase()) ||
description.toLowerCase().contains(other.toLowerCase()) ||
longDescription.toLowerCase().contains(other.toLowerCase())
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
package org.nwapw.abacus.tree
/**
* Reducer interface that takes a tree and returns a single value.
*
* The reducer walks the tree, visiting the children first, converting them into
* a value, and then attempts to reduce the parent. Eventually, the single final value is returned.
*/
interface Reducer <out T> {
/**
* Reduces the given tree node, given its already reduced children.
*
* @param treeNode the tree node to reduce.
* @param children the list of children, of type T.
*/
fun reduceNode(treeNode: TreeNode, vararg children: Any) : T?
}

View File

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

View File

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

View File

@@ -57,9 +57,19 @@
<Button text="Apply" onAction="#performSave"/> <Button text="Apply" onAction="#performSave"/>
<Button text="Reload Plugins" onAction="#performReload"/> <Button text="Reload Plugins" onAction="#performReload"/>
<Button text="Apply and Reload" onAction="#performSaveAndReload"/> <Button text="Apply and Reload" onAction="#performSaveAndReload"/>
<Button text="Scan Plugins" onAction="#performScan"/>
</FlowPane> </FlowPane>
</GridPane> </GridPane>
</Tab> </Tab>
<Tab fx:id="functionListTab" text="Functions" closable="false">
<VBox spacing="10">
<padding>
<Insets left="10" right="10" top="10" bottom="10"/>
</padding>
<TextField fx:id="functionListSearchField" maxWidth="Infinity"/>
<ListView maxWidth="Infinity" fx:id="functionListView"/>
</VBox>
</Tab>
</TabPane> </TabPane>
</center> </center>

View File

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