-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4ndyMath.js
More file actions
243 lines (229 loc) · 9.21 KB
/
4ndyMath.js
File metadata and controls
243 lines (229 loc) · 9.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Name: 4ndyMath.js Ver: 3.5.0
// Made by 4ndy64
(() => {
const _4ndyMath = {
VERSION: '3.5.0',
_cache: new Map(),
_functions: {
sin: { fn: Math.sin, d: (u, du) => ({ type: 'operator', op: '*', left: { type: 'function', name: 'cos', arg: u }, right: du }) },
cos: { fn: Math.cos, d: (u, du) => ({
type: 'operator', op: '*',
left: { type: 'operator', op: '*', left: { type: 'number', value: -1 }, right: { type: 'function', name: 'sin', arg: u } },
right: du
}) },
tan: { fn: Math.tan, d: (u, du) => ({
type: 'operator', op: '*',
left: { type: 'operator', op: '^', left: { type: 'function', name: 'sec', arg: u }, right: { type: 'number', value: 2 } },
right: du
}) },
ln: { fn: Math.log, d: (u, du) => ({
type: 'operator', op: '/', left: du, right: u
}) },
log: { fn: (x) => Math.log10(x), d: (u, du) => ({
type: 'operator', op: '/', left: du,
right: { type: 'operator', op: '*', left: u, right: { type: 'number', value: Math.LN10 } }
}) },
sqrt: { fn: Math.sqrt, d: (u, du) => ({
type: 'operator', op: '/',
left: du,
right: { type: 'operator', op: '*', left: { type: 'number', value: 2 }, right: { type: 'function', name: 'sqrt', arg: u } }
}) },
exp: { fn: Math.exp, d: (u, du) => ({
type: 'operator', op: '*', left: { type: 'function', name: 'exp', arg: u }, right: du
}) },
sec: { fn: (x) => 1/Math.cos(x), d: (u, du) => ({
type: 'operator', op: '*',
left: {
type: 'operator', op: '*',
left: { type: 'function', name: 'sec', arg: u },
right: { type: 'function', name: 'tan', arg: u }
},
right: du
}) }
},
_validate: {
input: (expr) => {
if (typeof expr !== 'string') throw new Error('Input must be a string');
if (expr.match(/[^a-z0-9\s+\-*/·×÷^(),.]/gi)) throw new Error('Invalid characters in expression');
},
division: (n) => {
if (n === 0) throw new Error('Division by zero');
}
},
tokenize: function(expr) {
this._validate.input(expr);
const tokenRegex = /(\d+\.?\d*|\.\d+)|([a-zA-Z_πφ]+)|([+\-*/·×÷^(),=])/g;
const tokens = [];
let match;
while ((match = tokenRegex.exec(expr)) !== null) {
if (match[1]) {
tokens.push({ type: 'number', value: parseFloat(match[1]) });
} else if (match[2]) {
tokens.push({ type: 'variable', value: match[2] });
} else if (match[3]) {
const char = match[3];
if (char === ',') {
tokens.push({ type: 'comma', value: char });
} else {
tokens.push({ type: 'operator', value: char });
}
}
}
for (let i = 0; i < tokens.length; i++) {
if (tokens[i].type === 'variable' && this._functions[tokens[i].value.toLowerCase()]) {
if (i + 1 < tokens.length && tokens[i + 1].type === 'operator' && tokens[i + 1].value === '(') {
tokens[i].type = 'function';
tokens[i].value = tokens[i].value.toLowerCase();
}
}
}
return this._addImplicitMultiplication(tokens);
},
_solveLinearSystem: (system) => {
const matrix = system.map(eq => [...Object.values(eq.coefficients), eq.constant]);
const n = matrix.length;
for (let i = 0; i < n; i++) {
let maxRow = i;
for (let j = i + 1; j < n; j++) {
if (Math.abs(matrix[j][i]) > Math.abs(matrix[maxRow][i])) {
maxRow = j;
}
}
[matrix[i], matrix[maxRow]] = [matrix[maxRow], matrix[i]];
const pivot = matrix[i][i];
if (Math.abs(pivot) < 1e-8) throw new Error('Matrix is singular');
for (let j = i + 1; j < n; j++) {
const factor = matrix[j][i] / pivot;
for (let k = i; k < n + 1; k++) {
matrix[j][k] -= factor * matrix[i][k];
}
}
}
const solution = new Array(n);
for (let i = n - 1; i >= 0; i--) {
solution[i] = matrix[i][n];
for (let j = i + 1; j < n; j++) {
solution[i] -= matrix[i][j] * solution[j];
}
solution[i] /= matrix[i][i];
}
return solution;
},
evaluate: function(expr, variables = {}) {
const cacheKey = `eval:${expr}:${JSON.stringify(variables)}`;
if (this._cache.has(cacheKey)) return this._cache.get(cacheKey);
const tokens = this.tokenize(expr);
const rpn = this.parseToRPN(tokens);
const result = this._evaluateRPN_withVariables(rpn, variables);
this._cache.set(cacheKey, result);
return result;
},
_buildExpressionTree: function(rpn) {
const stack = [];
rpn.forEach(token => {
if (token.type === 'number' || token.type === 'variable') {
stack.push({ type: token.type, value: token.value });
} else if (token.type === 'function') {
const arg = stack.pop();
stack.push({ type: 'function', name: token.value, arg });
} else if (token.type === 'operator') {
const right = stack.pop();
const left = stack.pop();
stack.push({ type: 'operator', op: token.value, left, right });
}
});
if (stack.length !== 1) throw new Error('Invalid expression tree');
return stack[0];
},
differentiate: function(expr, variable = 'x') {
const tokens = this.tokenize(expr);
const rpn = this.parseToRPN(tokens);
const tree = this._buildExpressionTree(rpn);
const dTree = this._differentiateTree(tree, variable);
return this._treeToString(dTree);
},
_differentiateTree: function(node, variable) {
// Constant: derivative is 0
if (node.type === 'number') {
return { type: 'number', value: 0 };
}
// Variable: derivative is 1 if matches, else 0
if (node.type === 'variable') {
return { type: 'number', value: node.value === variable ? 1 : 0 };
}
if (node.type === 'operator') {
const op = node.op;
const u = node.left, v = node.right;
const du = this._differentiateTree(u, variable);
const dv = this._differentiateTree(v, variable);
switch(op) {
case '+': return { type: 'operator', op: '+', left: du, right: dv };
case '-': return { type: 'operator', op: '-', left: du, right: dv };
case '*': return {
type: 'operator', op: '+',
left: { type: 'operator', op: '*', left: du, right: v },
right: { type: 'operator', op: '*', left: u, right: dv }
};
case '/': return {
type: 'operator', op: '/',
left: { type: 'operator', op: '-',
left: { type: 'operator', op: '*', left: du, right: v },
right: { type: 'operator', op: '*', left: u, right: dv } },
right: { type: 'operator', op: '^', left: v, right: { type: 'number', value: 2 } }
};
case '^':
if (v.type === 'number') {
// d/dx u^c = c*u^(c-1)*du
return {
type: 'operator', op: '*',
left: { type: 'operator', op: '*', left: v, right: { type: 'operator', op: '^', left: u, right: { type: 'number', value: v.value - 1 } } },
right: du
};
} else if (u.type === 'number') {
// d/dx c^v = c^v * ln(c)*dv
return {
type: 'operator', op: '*',
left: { type: 'operator', op: '^', left: u, right: v },
right: { type: 'operator', op: '*', left: { type: 'function', name: 'ln', arg: u }, right: dv }
};
} else {
// General: u^v * (v' ln(u) + v*u'/u)
return {
type: 'operator', op: '*',
left: { type: 'operator', op: '^', left: u, right: v },
right: {
type: 'operator', op: '+',
left: { type: 'operator', op: '*', left: dv, right: { type: 'function', name: 'ln', arg: u } },
right: { type: 'operator', op: '/', left: { type: 'operator', op: '*', left: v, right: du }, right: u }
}
};
}
default:
throw new Error(`Unsupported operator for differentiation: ${op}`);
}
}
if (node.type === 'function') {
const func = node.name;
const u = node.arg;
const du = this._differentiateTree(u, variable);
if (!this._functions.hasOwnProperty(func)) {
throw new Error(`No derivative rule for function ${func}`);
}
return this._functions[func].d(u, du);
}
throw new Error("Unknown node type in differentiation");
},
_treeToString: function(node) {
if (node.type === 'number') return node.value.toString();
if (node.type === 'variable') return node.value;
if (node.type === 'operator') {
return `(${this._treeToString(node.left)} ${node.op} ${this._treeToString(node.right)})`;
}
if (node.type === 'function') {
return `${node.name}(${this._treeToString(node.arg)})`;
}
return '';
}
};
window._4ndyMath = _4ndyMath;
})();