-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculatorcore.cpp
More file actions
490 lines (427 loc) · 14.4 KB
/
Copy pathcalculatorcore.cpp
File metadata and controls
490 lines (427 loc) · 14.4 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
#include "calculatorcore.h"
#include <QStack>
#include <QRegularExpression>
#include <QtMath>
#include <cmath>
#include <limits>
CalculatorCore::CalculatorCore() {}
CalculatorCore::Result CalculatorCore::compute(const QString &expression){
QVector<Token> tokens;
QString err;
if (!tokenize(expression, tokens, err)){
return { "ERR: " + err, true, err };
}
QVector<Token> rpn;
if (!toRpn(tokens, rpn, err)){
return { "ERR: " + err, true, err };
}
long double v = 0;
if (!evalRpn(rpn, v, err)){
if (err.isEmpty()) err = "Unknown Error";
return { "ERR: " + err, true, err };
}
if (std::isinf(v)){
return { "ERR: Factorial/Math Overflow", true, "Overflow" };
}
return { toHexFloatString(v, 12), false, "" };
}
long double CalculatorCore::fastPow(long double base, long long exp){
bool negExp = exp < 0;
if (negExp) exp = -exp;
long double result = 1.0L;
while (exp > 0) {
if (exp & 1) { // 二进制最低位为1
result *= base;
}
base *= base; // base 自乘
exp >>= 1; // 右移一位
}
return negExp ? (1.0L / result) : result;
}
// 通用幂运算 - 整数指数用快速幂,非整数用标准库
long double CalculatorCore::safePow(long double a, long double b){
long long intExp = static_cast<long long>(b);
if (static_cast<long double>(intExp) == b && std::abs(intExp) < 64){
return fastPow(a, intExp); // 整数快速幂
}
return std::powl(a, b); // 非整数标准库
}
long double CalculatorCore::factorial(long long n){
if (n < 0) return std::numeric_limits<long double>::quiet_NaN();
if (n > 22) return std::numeric_limits<long double>::infinity();
if (n <= 1) return 1.0L;
long double result = 1.0L;
for (long long i = 1; i <= n; ++i){
result *= i;
if (std::isinf(result) || result <= 0){
return std::numeric_limits<long double>::infinity();
}
}
return result;
}
bool CalculatorCore::parseHexFloat(const QString &s, long double &out, QString &err){
// 这里只做近似 转为 long double
QString t = s.toUpper();
bool neg = false;
if (t.startsWith('+')) t.remove(0, 1);
else if (t.startsWith('-')) { neg = true; t.remove(0, 1); }
const QStringList parts = t.split('.', Qt::KeepEmptyParts);
if (parts.size() > 2) { err = "invalid hex float"; return false; }
auto hexDigit = [](QChar c) -> int{
if (c.isDigit()) return c.unicode() - '0';
if (c >= 'A' && c <= 'F') return 10 + (c.unicode() - 'A');
return -1;
};
long double intPart = 0;
if (!parts[0].isEmpty()){
for (QChar c : parts[0]) {
int d = hexDigit(c);
if (d < 0) {
err = "invalid digit in integer part";
return false;
}
intPart = intPart * 16 + d;
}
}
long double fracPart = 0;
if (parts.size() == 2 && !parts[1].isEmpty()){
long double base = 16;
for (QChar c : parts[1]) {
int d = hexDigit(c);
if (d < 0){
err = "invalid digit in fractional part";
return false;
}
fracPart += (static_cast<long double>(d) / base);
base *= 16;
}
}
out = intPart + fracPart;
if (neg) out = -out;
return true;
}
QString CalculatorCore::toHexFloatString(long double v, int fracDigits){
if (std::isnan(v)) return "NAN";
if (std::isinf(v)) return (v > 0 ? "INF" : "-INF");
bool neg = v < 0;
if (neg) v = -v;
if (v > static_cast<long double>(std::numeric_limits<quint64>::max())){
QString s = QString::number(static_cast<double>(v), 'g', 15);
if (neg) s.prepend('-');
return s;
}
quint64 intPart = static_cast<quint64>(v);
long double frac = v - static_cast<long double>(intPart);
QString intStr = QString::number(intPart, 16).toUpper();
if (intStr.isEmpty()) intStr = "0";
QString fracStr;
for (int i = 0; i < fracDigits; i++){
frac *= 16;
int digit = static_cast<int>(frac);
if (digit < 0) digit = 0;
if (digit > 15) digit = 15;
frac -= digit;
fracStr += QString("0123456789ABCDEF")[digit];
if (frac == 0) break;
}
while (!fracStr.isEmpty() && fracStr.endsWith('0')) fracStr.chop(1);
QString out = intStr;
if (!fracStr.isEmpty()) out += "." + fracStr;
if (neg) out.prepend('-');
return out;
}
int CalculatorCore::precedence(const QString &op) const{
if (op == "!" || op == "~") return 6;
if (op == "^") return 5;
if (op == "*" || op == "/" || op == "%") return 4;
if (op == "+" || op == "-") return 3;
if (op == "<<" || op == ">>") return 2;
if (op == "&") return 1;
if (op == "^^") return 0;
if (op == "|") return -1;
return -10;
}
bool CalculatorCore::isLeftAssociative(const QString &op) const{
if (op == "^") return false;
if (op == "~") return false;
return true;
}
bool CalculatorCore::tokenize(const QString &expr, QVector<Token> &outTokens, QString &err) const{
outTokens.clear();
if (expr.isEmpty()){
err = "empty expression";
return false;
}
int i = 0;
auto isHex = [](QChar c){
return c. isDigit() || (c >= 'A' && c <= 'F');
};
while (i < expr. size()){
const QChar c = expr[i];
if (c.isSpace()){
i++;
continue;
}
if (c == '('){
outTokens.push_back({TokType::LParen, "("});
i++;
continue;
}
if (c == ')'){
outTokens.push_back({TokType::RParen, ")"});
i++;
continue;
}
if (c == '!'){
outTokens.push_back({TokType:: UnaryPostOp, "!"});
i++;
continue;
}
if (c == '~'){
outTokens.push_back({TokType:: UnaryPreOp, "~"});
i++;
continue;
}
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '&' || c == '|'){
outTokens.push_back({TokType::Op, QString(c)});
i++;
continue;
}
if (c == '^' || c == '<' || c == '>'){
int j = i + 1;
while (j < expr. size() && expr[j].isSpace()) j++;
if (j < expr.size() && expr[j] == c){
outTokens.push_back({TokType::Op, QString(c) + QString(c)});
i = j + 1;
} else if (c == '^'){
outTokens. push_back({TokType::Op, "^"});
i++;
} else {
err = QString("invalid operator '%1', did you mean '%1%1'?").arg(c);
return false;
}
continue;
}
if (isHex(c) || c == '.'){
int start = i;
bool seenDot = false;
while (i < expr.size()){
QChar cc = expr[i];
if (cc == '.'){
if (seenDot) break;
seenDot = true;
i++;
continue;
}
if (isHex(cc)){
i++;
continue;
}
break;
}
const QString num = expr.mid(start, i - start);
if (num == "."){
err = "invalid number '.'";
return false;
}
outTokens.push_back({TokType::Number, num});
continue;
}
err = QString("unexpected char '%1'").arg(c);
return false;
}
return true;
}
bool CalculatorCore::toRpn(const QVector<Token> &tokens, QVector<Token> &outRpn, QString &err) const{
outRpn.clear();
QStack<Token> opStack;
for (const auto &t : tokens){
if (t.type == TokType::Number){
outRpn.push_back(t);
while (!opStack.isEmpty() && opStack.top().type == TokType::UnaryPreOp){
outRpn. push_back(opStack.pop());
}
continue;
}
if (t. type == TokType::UnaryPreOp){
opStack.push(t);
continue;
}
if (t.type == TokType::Op){
while (!opStack.isEmpty()){
const Token top = opStack.top();
if (top.type != TokType::Op) break;
const int p1 = precedence(t.text);
const int p2 = precedence(top.text);
if ((isLeftAssociative(t.text) && p1 <= p2) || (!isLeftAssociative(t.text) && p1 < p2)) {
outRpn.push_back(opStack.pop());
} else {
break;
}
}
opStack.push(t);
continue;
}
if (t.type == TokType::UnaryPostOp){
outRpn.push_back(t);
continue;
}
if (t.type == TokType::LParen){
opStack.push(t);
continue;
}
if (t.type == TokType::RParen){
bool matched = false;
while (!opStack.isEmpty()){
Token top = opStack.pop();
if (top.type == TokType::LParen){
matched = true;
break;
}
outRpn.push_back(top);
}
if (!matched){
err = "mismatched parentheses";
return false;
}
continue;
}
}
while (!opStack.isEmpty()){
const Token top = opStack.pop();
if (top.type == TokType::LParen || top.type == TokType::RParen) {
err = "mismatched parentheses";
return false;
}
outRpn.push_back(top);
}
return true;
}
bool CalculatorCore::evalRpn(const QVector<Token> &rpn, long double &outValue, QString &err) const{
QStack<long double> st;
for (const auto &t : rpn){
if (t.type == TokType::Number){
long double v = 0;
if (!parseHexFloat(t.text, v, err)) return false;
st.push(v);
continue;
}
if (t.type == TokType::UnaryPreOp){
if (st. size() < 1){
err = "not enough operands for bitwise NOT";
return false;
}
const long double a = st.pop();
if (t. text == "~"){
long long intVal = static_cast<long long>(a);
if (static_cast<long double>(intVal) != a){
err = "bitwise NOT requires integer";
return false;
}
st.push(static_cast<long double>(~intVal));
}
continue;
}
if (t.type == TokType::Op){
if (st.size() < 2){
err = "not enough operands";
return false;
}
const long double b = st.pop();
const long double a = st.pop();
long double r = 0;
if (t.text == "+") r = a + b;
else if (t.text == "-") r = a - b;
else if (t.text == "*") r = a * b;
else if (t.text == "/") {
if (b == 0) {
err = "division by zero";
return false;
}
r = a / b;
} else if (t.text == "%"){
if (b ==0){
err = "modulo by zero";
return false;
}
r = std::fmodl(a,b);
} else if (t.text == "^"){
if (a == 0 && b <0){
err = "zero to negative power";
return false;
}
if (a < 0){
long long intExp = static_cast<long long>(b);
if (static_cast<long double>(intExp) != b){
err = "negative base with non-integer exponent";
return false;
}
}
r = safePow(a , b);
} else if (t.text == "&" || t.text == "|" || t.text == "^^" || t.text == "<<" || t.text == ">>") {
long long intA = static_cast<long long>(a);
long long intB = static_cast<long long>(b);
if (static_cast<long double>(intA) != a || static_cast<long double>(intB) != b){
err = "bitwise operations require integers";
return false;
}
if (t.text == "&") {
r = static_cast<long double>(intA & intB);
} else if (t.text == "|") {
r = static_cast<long double>(intA | intB);
} else if (t.text == "^^") {
r = static_cast<long double>(intA ^ intB);
} else if (t.text == "<<") {
if (intB < 0 || intB > 63) {
err = "shift amount out of range";
return false;
}
r = static_cast<long double>(intA << intB);
} else if (t. text == ">>") {
if (intB < 0 || intB > 63) {
err = "shift amount out of range";
return false;
}
r = static_cast<long double>(intA >> intB);
}
} else {
err = "unknown operator " + t.text;
return false;
}
st.push(r);
continue;
}
if (t.type == TokType::UnaryPostOp){
if (st.size() < 1){
err = "not enough operands for factorial";
return false;
}
const long double a = st.pop();
if (t. text == "!"){
if (a < 0){
err = "factorial of negative number";
return false;
}
long long intVal = static_cast<long long>(a);
if (static_cast<long double>(intVal) != a){
err = "factorial requires integer";
return false;
}
if (intVal > 22){
err = "factorial overflow";
return false;
}
st.push(factorial(intVal));
}
continue;
}
err = "invalid token in rpn";
return false;
}
if (st.size() != 1){
err = "invalid expression";
return false;
}
outValue = st.pop();
return true;
}