A parser for G.js that allows you to write mathematical expressions, which gets decomposed into Item Edit triggers efficiently.
Supports:
- Variable assignment (
n = ...) - Arithmetic (+ - * /)
- Exponentiation (^)
- Parentheses
- Unary operators (+ -)
- Factorials (!, only for integers, not variables)
- Some function calls like abs, round, rnd, floor, ceil
Code below generates and runs the Taylor series for sin(x) and cos(x):
import '@g-js-api/g.js';
import { setVariables, equation } from '@g-js-api/algebra';
await $.exportConfig({
type: 'live_editor',
options: { info: true, verticalPositioning: false } // verticalPositioning: false because horizontal order is necessary here
});
let result1 = float_counter(); // sin result
let result2 = float_counter(); // cos result
let input = float_counter(25); // 25 degrees
// constant for converting degrees to radians
// we also multiply by 1e+7 because item edit's mod field only has 3 digits of decimal precision,
// so we put as much of the decimal as we can into the integer part before info is lost
let radians_factor = float_counter(Math.PI / 180 * 1e+7);
// text + item displays so the user can see the inputs and outputs
$.add("Input:"
.to_obj()
.with(obj_props.X, 88)
.with(obj_props.Y, 125)
.with(obj_props.SCALING, 0.25));
input.display(88, 105);
$.add("Sine:"
.to_obj()
.with(obj_props.X, 45)
.with(obj_props.Y, 65)
.with(obj_props.SCALING, 0.25));
result1.display(45, 45);
$.add("Cosine:"
.to_obj()
.with(obj_props.X, 135)
.with(obj_props.Y, 65)
.with(obj_props.SCALING, 0.25));
result2.display(135, 45);
// define the variable names in the equations
radians_factor.divide(1e+7); // to bypass item edit's mod field precision
setVariables({
result1,
result2,
// here we copy the input degrees and multiply it by radians_factor to convert it to rads
x: input
.clone()
.multiply(radians_factor)
})
// 6 terms for the Taylor series
let terms = 6;
let sin_str = [];
let cos_str = [];
// sin and cos Taylor series are calcualted simultaneously
// a term for sin(x): ±(x ^ n / n!) where n is an odd number
// a term for cos(x): ±(x ^ n / n!) where n is an even number
// for both cases, the sign alternates between + and -
for (let n = 0; n < terms; n++) {
let power = 2 * n;
let sign = n % 2 === 0 ? "" : "-";
sin_str.push(`${sign}(x ^ ${power + 1} / ${power + 1}!)`);
cos_str.push(`${sign}(x ^ ${power} / ${power}!)`);
}
// `equation(string)` takes an equation as input and adds Item Edit triggers as output
// here, we sum the terms for sin and cos
equation(`result1 = ${sin_str.join('+')}`); // sin
equation(`result2 = ${cos_str.join('+')}`); // cos