-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemp-engine.js
More file actions
759 lines (672 loc) · 32.9 KB
/
temp-engine.js
File metadata and controls
759 lines (672 loc) · 32.9 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
const AdvancedMathEngine = {
// Константы
constants: {
'pi': Math.PI,
'e': Math.E,
'phi': (1 + Math.sqrt(5)) / 2, // Золотое сечение
'ln2': Math.LN2,
'ln10': Math.LN10,
'log2e': Math.LOG2E,
'log10e': Math.LOG10E,
'sqrt1_2': Math.SQRT1_2,
'sqrt2': Math.SQRT2,
'infinity': Infinity,
'inf': Infinity
},
// Расширенные функции
functions: {
// Тригонометрия
'sin': Math.sin,
'cos': Math.cos,
'tan': Math.tan,
'asin': Math.asin,
'acos': Math.acos,
'atan': Math.atan,
'atan2': Math.atan2,
'sinh': Math.sinh,
'cosh': Math.cosh,
'tanh': Math.tanh,
'asinh': Math.asinh,
'acosh': Math.acosh,
'atanh': Math.atanh,
// Логарифмы и экспоненты
'log': Math.log10,
'ln': Math.log,
'log2': Math.log2,
'exp': Math.exp,
'expm1': Math.expm1,
'log1p': Math.log1p,
// Степени и корни
'sqrt': Math.sqrt,
'cbrt': Math.cbrt,
'pow': Math.pow,
'root': function(n, x) { return Math.pow(x, 1/n); },
// Округление
'abs': Math.abs,
'sign': Math.sign,
'floor': Math.floor,
'ceil': Math.ceil,
'round': Math.round,
'trunc': Math.trunc,
'frac': function(x) { return x - Math.trunc(x); },
// Минимум и максимум
'min': Math.min,
'max': Math.max,
// Случайные числа
'random': Math.random,
'randomInt': function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
// Дополнительные функции
'factorial': function(n) {
if (n < 0 || !Number.isInteger(n)) return NaN;
if (n <= 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
if (!isFinite(result)) return Infinity;
}
return result;
},
'gcd': function(a, b) {
a = Math.abs(Math.trunc(a));
b = Math.abs(Math.trunc(b));
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
},
'lcm': function(a, b) {
return Math.abs(a * b) / this.gcd(a, b);
},
'deg': function(rad) {
return rad * 180 / Math.PI;
},
'rad': function(deg) {
return deg * Math.PI / 180;
},
'mod': function(a, b) {
return ((a % b) + b) % b;
},
'isPrime': function(n) {
n = Math.trunc(n);
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
},
'fibonacci': function(n) {
n = Math.trunc(n);
if (n <= 0) return 0;
if (n === 1) return 1;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
},
'combinations': function(n, r) {
n = Math.trunc(n);
r = Math.trunc(r);
if (r > n || r < 0) return 0;
if (r === 0 || r === n) return 1;
r = Math.min(r, n - r);
let result = 1;
for (let i = 0; i < r; i++) {
result *= (n - i) / (i + 1);
}
return Math.round(result);
},
'permutations': function(n, r) {
n = Math.trunc(n);
r = Math.trunc(r);
if (r > n || r < 0) return 0;
let result = 1;
for (let i = 0; i < r; i++) {
result *= (n - i);
}
return result;
},
// Дроби
'toFraction': function(decimal, tolerance = 1e-10) {
let h1 = 1, h2 = 0, k1 = 0, k2 = 1;
let b = decimal;
do {
let a = Math.floor(b);
let aux = h1; h1 = a * h1 + h2; h2 = aux;
aux = k1; k1 = a * k1 + k2; k2 = aux;
b = 1 / (b - a);
} while (Math.abs(decimal - h1/k1) > tolerance && k1 < 1000000);
return {numerator: h1, denominator: k1, string: h1 + '/' + k1};
}
},
// Улучшенная токенизация с поддержкой дробей, процентов, модулей и Unicode символов
tokenize: function(expr) {
// Нормализация Unicode математических символов
expr = expr
.replace(/−/g, '-') // Unicode минус → обычный минус
.replace(/×/g, '*') // Unicode умножение → звездочка
.replace(/÷/g, '/') // Unicode деление → слэш
.replace(/π/g, 'pi') // Unicode пи → pi
.replace(/∞/g, 'Infinity') // Unicode бесконечность
.replace(/√/g, 'sqrt') // Unicode корень → sqrt
.replace(/²/g, '^2') // Unicode степень 2
.replace(/³/g, '^3') // Unicode степень 3
.replace(/⁻¹/g, '^(-1)') // Unicode обратная степень
.replace(/∑/g, 'sum') // Unicode сумма
.replace(/∏/g, 'product') // Unicode произведение
.replace(/∫/g, 'integral') // Unicode интеграл
.replace(/≈/g, '~') // Unicode приблизительно равно
.replace(/≠/g, '!=') // Unicode не равно
.replace(/≤/g, '<=') // Unicode меньше или равно
.replace(/≥/g, '>=') // Unicode больше или равно
.replace(/⋅/g, '*') // Unicode точка умножения
.replace(/∘/g, '*') // Unicode композиция функций
.replace(/∙/g, '*'); // Unicode bullet operator
const tokens = [];
let i = 0;
while (i < expr.length) {
const char = expr[i];
// Пропускаем пробелы
if (/\s/.test(char)) {
i++;
continue;
}
// Обработка модуля |...|
if (char === '|') {
// Проверяем, это открывающий или закрывающий модуль
// Ищем предыдущий незакрытый ABS_START
let hasOpenAbs = false;
for (let j = tokens.length - 1; j >= 0; j--) {
if (tokens[j].type === 'ABS_END') {
break; // Найден закрывающий, значит предыдущий ABS_START уже закрыт
}
if (tokens[j].type === 'ABS_START') {
hasOpenAbs = true;
break;
}
}
if (hasOpenAbs) {
tokens.push({ type: 'ABS_END' });
} else {
tokens.push({ type: 'ABS_START' });
}
i++;
continue;
}
// Обработка квадратного корня √
if (char === '√') {
tokens.push({ type: 'FUNCTION', value: 'sqrt' });
i++;
continue;
}
// Числа с поддержкой дробей a/b
if (/\d/.test(char) || (char === '.' && i + 1 < expr.length && /\d/.test(expr[i + 1]))) {
let num = '';
let j = i;
// Читаем первое число
while (j < expr.length && (/\d/.test(expr[j]) || expr[j] === '.')) {
num += expr[j++];
}
// Проверяем, есть ли дробь
if (j < expr.length && expr[j] === '/' && j + 1 < expr.length && /\d/.test(expr[j + 1])) {
num += '/';
j++;
while (j < expr.length && /\d/.test(expr[j])) {
num += expr[j++];
}
// Парсим дробь
const parts = num.split('/');
const numerator = parseFloat(parts[0]);
const denominator = parseFloat(parts[1]);
if (denominator === 0) throw new Error('Деление на ноль в дроби');
tokens.push({ type: 'NUMBER', value: numerator / denominator, original: num });
i = j;
continue;
}
// Проверяем научную нотацию
if (j < expr.length && (expr[j] === 'e' || expr[j] === 'E')) {
num += expr[j++];
if (j < expr.length && (expr[j] === '+' || expr[j] === '-')) {
num += expr[j++];
}
while (j < expr.length && /\d/.test(expr[j])) {
num += expr[j++];
}
}
const numValue = parseFloat(num);
if (isNaN(numValue)) {
throw new Error(`Некорректное число: ${num}`);
}
tokens.push({ type: 'NUMBER', value: numValue });
i = j;
continue;
}
// Процент %
if (char === '%') {
// Если это оператор процента (после числа)
if (tokens.length > 0 && tokens[tokens.length - 1].type === 'NUMBER') {
tokens.push({ type: 'PERCENT' });
} else {
// Это модуло оператор
tokens.push({ type: 'OPERATOR', value: '%' });
}
i++;
continue;
}
// Операторы и символы (поддержка Unicode минуса)
if ('+-*/^()'.includes(char) || char === '−') {
// Заменяем Unicode минус на обычный минус
const normalizedChar = char === '−' ? '-' : char;
tokens.push({ type: 'OPERATOR', value: normalizedChar });
i++;
continue;
}
// Двойная звездочка ** для степени
if (char === '*' && i + 1 < expr.length && expr[i + 1] === '*') {
tokens.push({ type: 'OPERATOR', value: '^' });
i += 2;
continue;
}
// Запятая как разделитель аргументов функций
if (char === ',') {
tokens.push({ type: 'COMMA' });
i++;
continue;
}
// Функции и константы
if (/[a-zA-Z_]/.test(char)) {
let name = '';
while (i < expr.length && (/[a-zA-Z_0-9]/.test(expr[i]))) {
name += expr[i++];
}
if (this.functions[name]) {
tokens.push({ type: 'FUNCTION', value: name });
} else if (this.constants[name]) {
tokens.push({ type: 'NUMBER', value: this.constants[name] });
} else {
throw new Error(`Неизвестная функция или константа: ${name}`);
}
continue;
}
// Факториал
if (char === '!') {
tokens.push({ type: 'FACTORIAL' });
i++;
continue;
}
throw new Error(`Неожиданный символ: ${char} на позиции ${i}`);
}
return tokens;
},
// Улучшенный парсинг в обратную польскую нотацию с поддержкой модулей и процентов
toRPN: function(tokens) {
const output = [];
const operators = [];
const precedence = {
'+': 1, '-': 1,
'*': 2, '/': 2, '%': 2,
'^': 4,
'u-': 5, // унарный минус
'u+': 5 // унарный плюс
};
const rightAssoc = { '^': true };
const argCounts = []; // Стек для подсчета аргументов функций
let absStack = []; // Стек для отслеживания модулей
// Предварительная обработка для унарных операторов
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
const prevToken = i > 0 ? tokens[i - 1] : null;
// Определяем унарный минус и плюс
if (token.type === 'OPERATOR' && (token.value === '-' || token.value === '+')) {
if (i === 0 ||
(prevToken && (prevToken.type === 'OPERATOR' && prevToken.value === '(' ||
prevToken.type === 'COMMA' ||
(prevToken.type === 'OPERATOR' && prevToken.value !== ')')))) {
token.value = 'u' + token.value;
token.unary = true;
}
}
}
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.type === 'NUMBER') {
output.push(token);
// Увеличиваем счетчик аргументов для текущей функции
if (argCounts.length > 0) {
argCounts[argCounts.length - 1]++;
}
} else if (token.type === 'ABS_START') {
// Начало модуля - добавляем как функцию abs
operators.push({ type: 'FUNCTION', value: 'abs' });
operators.push({ type: 'OPERATOR', value: '(' });
argCounts.push(0);
absStack.push(operators.length - 1);
} else if (token.type === 'ABS_END') {
// Конец модуля - закрываем функцию abs
while (operators.length && operators[operators.length - 1].value !== '(') {
output.push(operators.pop());
}
if (operators.length && operators[operators.length - 1].value === '(') {
operators.pop(); // Убираем '('
// Добавляем функцию abs
if (operators.length && operators[operators.length - 1].type === 'FUNCTION') {
const func = operators.pop();
output.push(func);
argCounts.pop();
}
}
if (absStack.length > 0) {
absStack.pop();
}
} else if (token.type === 'FUNCTION') {
operators.push(token);
argCounts.push(0); // Начинаем подсчет аргументов для новой функции
} else if (token.type === 'COMMA') {
// Обрабатываем запятую как разделитель аргументов
while (operators.length && operators[operators.length - 1].value !== '(') {
output.push(operators.pop());
}
if (argCounts.length > 0) {
argCounts[argCounts.length - 1]++;
}
} else if (token.type === 'PERCENT') {
// Преобразуем последнее число в проценты (делим на 100)
if (output.length > 0 && output[output.length - 1].type === 'NUMBER') {
output[output.length - 1].value = output[output.length - 1].value / 100;
}
} else if (token.type === 'OPERATOR') {
if (token.value === '(') {
operators.push(token);
} else if (token.value === ')' || token.value === '|') {
// Закрытие скобки или модуля
while (operators.length && operators[operators.length - 1].value !== '(') {
output.push(operators.pop());
}
if (operators.length) {
operators.pop(); // Убираем '('
}
// Если это было закрытие модуля
if (token.value === '|' && absStack.length > 0) {
absStack.pop();
}
if (operators.length && operators[operators.length - 1].type === 'FUNCTION') {
const func = operators.pop();
const argCount = argCounts.length > 0 ? argCounts.pop() : 1;
func.argCount = argCount || 1;
output.push(func);
}
} else if (token.unary) {
// Унарные операторы имеют высокий приоритет
operators.push(token);
} else {
// Бинарные операторы
while (operators.length &&
operators[operators.length - 1].value !== '(' &&
operators[operators.length - 1].type !== 'FUNCTION' &&
!operators[operators.length - 1].unary &&
((precedence[operators[operators.length - 1].value] || 0) > precedence[token.value] ||
(precedence[operators[operators.length - 1].value] === precedence[token.value] && !rightAssoc[token.value]))) {
output.push(operators.pop());
}
operators.push(token);
}
} else if (token.type === 'FACTORIAL') {
output.push(token);
}
}
while (operators.length) {
const op = operators.pop();
if (op.type === 'FUNCTION') {
op.argCount = op.argCount || 1; // Функция без скобок имеет 1 аргумент
}
output.push(op);
}
return output;
},
// Улучшенное вычисление RPN с поддержкой всех операций
evaluateRPN: function(rpn) {
const stack = [];
for (const token of rpn) {
if (token.type === 'NUMBER') {
stack.push(token.value);
} else if (token.type === 'OPERATOR') {
if (token.unary) {
// Унарные операторы
const a = stack.pop();
if (a === undefined) throw new Error(`Недостаточно операндов для унарного ${token.value}`);
if (token.value === 'u-') {
stack.push(-a);
} else if (token.value === 'u+') {
stack.push(+a);
}
} else {
// Бинарные операторы
const b = stack.pop();
const a = stack.pop();
if (a === undefined || b === undefined) {
throw new Error(`Недостаточно операндов для ${token.value}`);
}
switch (token.value) {
case '+':
stack.push(a + b);
break;
case '-':
stack.push(a - b);
break;
case '*':
stack.push(a * b);
break;
case '/':
if (b === 0) throw new Error('Деление на ноль');
stack.push(a / b);
break;
case '%':
if (b === 0) throw new Error('Деление на ноль в операции модуло');
stack.push(a % b);
break;
case '^':
stack.push(Math.pow(a, b));
break;
default:
throw new Error(`Неизвестный оператор: ${token.value}`);
}
}
} else if (token.type === 'FUNCTION') {
const func = this.functions[token.value];
if (!func) throw new Error(`Неизвестная функция: ${token.value}`);
const argCount = token.argCount || 1;
const args = [];
for (let i = 0; i < argCount; i++) {
const arg = stack.pop();
if (arg === undefined) {
throw new Error(`Недостаточно аргументов для функции ${token.value}`);
}
args.unshift(arg);
}
try {
const result = func.apply(this.functions, args);
if (typeof result !== 'number' || !isFinite(result)) {
if (token.value === 'factorial' && !isFinite(result)) {
stack.push(Infinity);
} else {
throw new Error(`Функция ${token.value} вернула некорректный результат`);
}
} else {
stack.push(result);
}
} catch (error) {
throw new Error(`Ошибка в функции ${token.value}: ${error.message}`);
}
} else if (token.type === 'FACTORIAL') {
const a = stack.pop();
if (a === undefined) throw new Error('Недостаточно операндов для факториала');
const result = this.functions.factorial(a);
stack.push(result);
}
}
if (stack.length !== 1) {
throw new Error('Некорректное выражение: неверный баланс операций');
}
return stack[0];
},
// Основная функция вычисления - самый мощный движок!
evaluate: function(expression) {
try {
// Предварительная обработка
let expr = expression.toString()
.replace(/\s+/g, ' ')
.trim();
if (!expr) throw new Error('Пустое выражение');
// Заменяем альтернативные символы и нотации
expr = expr.replace(/\*\*/g, '^') // ** → ^
.replace(/×/g, '*') // × → *
.replace(/÷/g, '/') // ÷ → /
.replace(/√/g, 'sqrt') // √ → sqrt
.replace(/π/g, 'pi') // π → pi
.replace(/∞/g, 'infinity') // ∞ → infinity
.replace(/±/g, '+/-') // ± → +/-
.replace(/∓/g, '-/+') // ∓ → -/+
.replace(/≠/g, '!=') // ≠ → !=
.replace(/≤/g, '<=') // ≤ → <=
.replace(/≥/g, '>=') // ≥ → >=
.replace(/∑/g, 'sum') // ∑ → sum
.replace(/∏/g, 'product') // ∏ → product
.replace(/∫/g, 'integral') // ∫ → integral
.replace(/∂/g, 'partial') // ∂ → partial
.replace(/∇/g, 'nabla') // ∇ → nabla
.replace(/∀/g, 'forall') // ∀ → forall
.replace(/∃/g, 'exists') // ∃ → exists
.replace(/∈/g, 'in') // ∈ → in
.replace(/∉/g, 'notin') // ∉ → notin
.replace(/⊂/g, 'subset') // ⊂ → subset
.replace(/⊃/g, 'superset') // ⊃ → superset
.replace(/∪/g, 'union') // ∪ → union
.replace(/∩/g, 'intersection'); // ∩ → intersection
// Обработка процентов в контексте (50% от 200 = 50/100 * 200)
expr = expr.replace(/(\d+(?:\.\d+)?)\s*%\s*от\s*(\d+(?:\.\d+)?)/gi, '($1/100)*$2');
expr = expr.replace(/(\d+(?:\.\d+)?)\s*%\s*of\s*(\d+(?:\.\d+)?)/gi, '($1/100)*$2');
// Обработка смешанных чисел (2 3/4 = 2 + 3/4)
expr = expr.replace(/(\d+)\s+(\d+\/\d+)/g, '($1+$2)');
// Добавляем поддержку неявного умножения
expr = expr.replace(/(\d)([a-z])/gi, '$1*$2'); // 2x → 2*x
expr = expr.replace(/([a-z])(\d)/gi, '$1*$2'); // x2 → x*2
expr = expr.replace(/(\))(\d)/g, '$1*$2'); // )2 → )*2
expr = expr.replace(/(\d)(\()/g, '$1*$2'); // 2( → 2*(
expr = expr.replace(/(\))(\()/g, '$1*$2'); // )( → )*(
expr = expr.replace(/([a-z])(\()/gi, '$1*$2'); // x( → x*(
expr = expr.replace(/(\d)(sqrt|sin|cos|tan|log|ln)/gi, '$1*$2'); // 2sin → 2*sin
// Обработка модулей |...|
let absCount = 0;
expr = expr.replace(/\|/g, () => {
absCount++;
return absCount % 2 === 1 ? '|' : '|';
});
// Проверяем парность модулей
if (absCount % 2 !== 0) {
throw new Error('Несбалансированные модули |...|');
}
// Обрабатываем унарный минус и плюс в начале и после операторов
expr = expr.replace(/^-/, '0-'); // Начальный минус
expr = expr.replace(/^\\+/, '0+'); // Начальный плюс
expr = expr.replace(/\(-/g, '(0-'); // После (
expr = expr.replace(/\(\\+/g, '(0+'); // После (
expr = expr.replace(/([+\-*/^%,])\s*-/g, '$10-'); // После операторов
expr = expr.replace(/([+\-*/^%,])\s*\\+/g, '$10+'); // После операторов
// Проверяем баланс скобок
let openParens = 0;
for (let char of expr) {
if (char === '(') openParens++;
else if (char === ')') openParens--;
if (openParens < 0) throw new Error('Несбалансированные скобки');
}
if (openParens !== 0) throw new Error('Несбалансированные скобки');
// Токенизация
const tokens = this.tokenize(expr);
if (tokens.length === 0) throw new Error('Пустое выражение');
// Преобразование в RPN
const rpn = this.toRPN(tokens);
// Вычисление
let result = this.evaluateRPN(rpn);
// Проверка результата
if (!isFinite(result)) {
if (result === Infinity) return '∞';
if (result === -Infinity) return '-∞';
throw new Error('Результат не является конечным числом');
}
// Форматирование результата с точностью до 10 знаков
if (Number.isInteger(result)) {
return result;
} else {
// Убираем лишние нули и ограничиваем точность
let formatted = parseFloat(result.toFixed(10));
// Проверяем, можно ли представить как простую дробь
if (Math.abs(formatted) < 1000000) {
const fraction = this.functions.toFraction(formatted, 1e-8);
if (fraction.denominator <= 1000 &&
Math.abs(formatted - fraction.numerator/fraction.denominator) < 1e-10) {
return `${formatted} (${fraction.string})`;
}
}
return formatted;
}
} catch (error) {
throw new Error(`Ошибка вычисления: ${error.message}`);
}
},
// Дополнительные утилиты для мощного движка
formatResult: function(value, options = {}) {
const { precision = 10, showFraction = true, scientific = false } = options;
if (!isFinite(value)) {
if (value === Infinity) return '∞';
if (value === -Infinity) return '-∞';
return 'NaN';
}
if (Number.isInteger(value)) {
return value.toString();
}
if (scientific && (Math.abs(value) >= 1e15 || Math.abs(value) <= 1e-5)) {
return value.toExponential(precision);
}
let result = parseFloat(value.toFixed(precision)).toString();
if (showFraction && Math.abs(value) < 1000) {
const fraction = this.functions.toFraction(value);
if (fraction.denominator <= 100) {
result += ` (${fraction.string})`;
}
}
return result;
},
// Проверка корректности выражения
validate: function(expression) {
try {
this.tokenize(expression);
return { valid: true, error: null };
} catch (error) {
return { valid: false, error: error.message };
}
},
// Получение информации о функциях и константах
getHelp: function() {
return {
constants: Object.keys(this.constants),
functions: Object.keys(this.functions),
operators: ['+', '-', '*', '/', '^', '%', '!', '|...|'],
examples: [
'sqrt(25) = 5',
'2^3 = 8',
'sin(pi/2) = 1',
'5! = 120',
'|3-7| = 4',
'50% = 0.5',
'1/2 + 1/3 = 0.833333 (5/6)',
'gcd(12, 18) = 6',
'combinations(5, 2) = 10'
]
};
}
};
module.exports = AdvancedMathEngine;