Compare commits

...

11 Commits

Author SHA1 Message Date
722ef9ca21 🚀 Launch 1.0.0+4 2025-09-14 03:16:47 +08:00
37e3e4ecd3 💄 Fix chart 2025-09-14 03:11:14 +08:00
bd97721dbc Function chart 2025-09-14 03:08:53 +08:00
a02325052c No real number solution 2025-09-14 02:46:54 +08:00
4c11866da0 💄 Optimize calculator input 2025-09-14 02:44:59 +08:00
18b4406ece Test the simplify of 2x^2+4x-3=0 2025-09-14 02:43:51 +08:00
bf74f8d176 💄 Better simplify 2025-09-14 02:42:43 +08:00
35ea42ce9b 🐛 Fix delta calculation 2025-09-14 02:33:02 +08:00
3f0bcb472d ♻️ Replaced with own calculator 2025-09-14 02:22:27 +08:00
90a77a2cba ♻️ New calculator pending to replace math_expressions 2025-09-13 23:56:17 +08:00
3795b659f6 💄 Improve accurate of sqrt calculation 2025-09-13 22:56:01 +08:00
11 changed files with 2052 additions and 258 deletions

View File

@@ -1,6 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="simple_math_calc"
android:label="SimpleMathCalc"
android:name="${applicationName}"
android:icon="@mipmap/launcher_icon">
<activity

539
lib/calculator.dart Normal file
View File

@@ -0,0 +1,539 @@
// === 在 abstract class Expr 中添加声明 ===
import 'dart:math' show sqrt, cos, sin, tan;
abstract class Expr {
Expr simplify();
/// 新增:对表达式进行“求值/数值化”——尽可能把可算的部分算出来
Expr evaluate();
@override
String toString();
MulExpr operator *(Expr other) => MulExpr(this, other);
AddExpr operator +(Expr other) => AddExpr(this, other);
SubExpr operator -(Expr other) => SubExpr(this, other);
DivExpr operator /(Expr other) => DivExpr(this, other);
}
// === IntExpr ===
class IntExpr extends Expr {
final int value;
IntExpr(this.value);
@override
Expr simplify() => this;
@override
Expr evaluate() => this;
@override
String toString() => value.toString();
}
// === DoubleExpr ===
class DoubleExpr extends Expr {
final double value;
DoubleExpr(this.value);
@override
Expr simplify() => this;
@override
Expr evaluate() => this;
@override
String toString() => value.toString();
}
// === FractionExpr.evaluate ===
class FractionExpr extends Expr {
final int numerator;
final int denominator;
FractionExpr(this.numerator, this.denominator) {
if (denominator == 0) throw Exception("分母不能为0");
}
@override
Expr simplify() {
int g = _gcd(numerator.abs(), denominator.abs());
int n = numerator ~/ g;
int d = denominator ~/ g;
// 分母负数转移到分子
if (d < 0) {
n = -n;
d = -d;
}
if (d == 1) return IntExpr(n); // 化简成整数
return FractionExpr(n, d);
}
@override
Expr evaluate() => simplify();
@override
String toString() => "$numerator/$denominator";
}
// === AddExpr.evaluate: 把可算的合并(整数、分数、以及同类 sqrt 项) ===
class AddExpr extends Expr {
final Expr left, right;
AddExpr(this.left, this.right);
@override
Expr simplify() {
var l = left.simplify();
var r = right.simplify();
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator + r.numerator * l.denominator,
l.denominator * r.denominator,
).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(
l.value * r.denominator + r.numerator,
r.denominator,
).simplify();
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(
l.numerator + r.value * l.denominator,
l.denominator,
).simplify();
}
return AddExpr(l, r);
}
@override
Expr evaluate() {
var l = left.evaluate();
var r = right.evaluate();
// 纯整数相加 -> 整数
if (l is IntExpr && r is IntExpr) {
return IntExpr(l.value + r.value);
}
// 分数相加 / 分数与整数相加
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator + r.numerator * l.denominator,
l.denominator * r.denominator,
).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(
l.value * r.denominator + r.numerator,
r.denominator,
).simplify();
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(
l.numerator + r.value * l.denominator,
l.denominator,
).simplify();
}
// 合并同类的 sqrt 项: a*sqrt(X) + b*sqrt(X) = (a+b)*sqrt(X)
var a = _asSqrtTerm(l);
var b = _asSqrtTerm(r);
if (a != null && b != null && a.inner.toString() == b.inner.toString()) {
return MulExpr(IntExpr(a.coef + b.coef), SqrtExpr(a.inner)).simplify();
}
return AddExpr(l, r);
}
@override
String toString() => "($left + $right)";
}
// === SubExpr.evaluate 类似 AddExpr但做减法 ===
class SubExpr extends Expr {
final Expr left, right;
SubExpr(this.left, this.right);
@override
Expr simplify() {
var l = left.simplify();
var r = right.simplify();
if (l is IntExpr && r is IntExpr) {
return IntExpr(l.value - r.value);
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator - r.numerator * l.denominator,
l.denominator * r.denominator,
).simplify();
}
return SubExpr(l, r);
}
@override
Expr evaluate() {
var l = left.evaluate();
var r = right.evaluate();
if (l is IntExpr && r is IntExpr) {
return IntExpr(l.value - r.value);
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator - r.numerator * l.denominator,
l.denominator * r.denominator,
).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(
l.value * r.denominator - r.numerator,
r.denominator,
).simplify();
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(
l.numerator - r.value * l.denominator,
l.denominator,
).simplify();
}
// 处理同类 sqrt 项: a*sqrt(X) - b*sqrt(X) = (a-b)*sqrt(X)
var a = _asSqrtTerm(l);
var b = _asSqrtTerm(r);
if (a != null && b != null && a.inner.toString() == b.inner.toString()) {
return MulExpr(IntExpr(a.coef - b.coef), SqrtExpr(a.inner)).simplify();
}
return SubExpr(l, r);
}
@override
String toString() => "($left - $right)";
}
// === MulExpr.evaluate ===
class MulExpr extends Expr {
final Expr left, right;
MulExpr(this.left, this.right);
@override
Expr simplify() {
var l = left.simplify();
var r = right.simplify();
if (l is IntExpr && l.value == 1) return r;
if (r is IntExpr && r.value == 1) return l;
if (l is IntExpr && l.value == -1) return SubExpr(IntExpr(0), r).simplify();
if (r is IntExpr && r.value == -1) return SubExpr(IntExpr(0), l).simplify();
if (l is IntExpr && r is IntExpr) {
return IntExpr(l.value * r.value);
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(l.numerator * r.value, l.denominator).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(l.value * r.numerator, r.denominator).simplify();
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.numerator,
l.denominator * r.denominator,
).simplify();
}
if (l is SqrtExpr && r is FractionExpr) {
return FractionExpr(1, r.denominator).simplify() *
MulExpr(l, IntExpr(r.numerator)).simplify();
}
return MulExpr(l, r);
}
@override
Expr evaluate() {
var l = left.evaluate();
var r = right.evaluate();
if (l is IntExpr && l.value == 1) return r;
if (r is IntExpr && r.value == 1) return l;
if (l is IntExpr && l.value == -1) return SubExpr(IntExpr(0), r).simplify();
if (r is IntExpr && r.value == -1) return SubExpr(IntExpr(0), l).simplify();
if (l is IntExpr && r is IntExpr) {
return IntExpr(l.value * r.value);
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(l.numerator * r.value, l.denominator).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(l.value * r.numerator, r.denominator).simplify();
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.numerator,
l.denominator * r.denominator,
).simplify();
}
// sqrt * sqrt: sqrt(a)*sqrt(a) = a
if (l is SqrtExpr &&
r is SqrtExpr &&
l.inner.toString() == r.inner.toString()) {
return l.inner.simplify();
}
// int * sqrt -> 保留形式,之后 simplify() 再处理约分
if ((l is IntExpr && r is SqrtExpr) || (l is SqrtExpr && r is IntExpr)) {
return MulExpr(l, r).simplify();
}
return MulExpr(l, r);
}
@override
String toString() => "($left * $right)";
}
// === DivExpr.evaluate ===
class DivExpr extends Expr {
final Expr left, right;
DivExpr(this.left, this.right);
@override
Expr simplify() {
var l = left.simplify();
var r = right.simplify();
if (l is IntExpr && r is IntExpr) {
return FractionExpr(l.value, r.value).simplify();
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(l.numerator, l.denominator * r.value).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(l.value * r.denominator, r.numerator).simplify();
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator,
l.denominator * r.numerator,
).simplify();
}
if (l is MulExpr &&
l.left is IntExpr &&
l.right is SqrtExpr &&
r is IntExpr) {
int coeff = (l.left as IntExpr).value;
int denom = r.value;
int g = _gcd(coeff.abs(), denom.abs());
return MulExpr(
IntExpr(coeff ~/ g),
DivExpr(l.right, IntExpr(denom ~/ g)).simplify(),
).simplify();
}
return DivExpr(l, r);
}
@override
Expr evaluate() {
var l = left.evaluate();
var r = right.evaluate();
if (l is IntExpr && r is IntExpr) {
return FractionExpr(l.value, r.value).simplify();
}
if (l is FractionExpr && r is IntExpr) {
return FractionExpr(l.numerator, l.denominator * r.value).simplify();
}
if (l is IntExpr && r is FractionExpr) {
return FractionExpr(l.value * r.denominator, r.numerator).simplify();
}
if (l is FractionExpr && r is FractionExpr) {
return FractionExpr(
l.numerator * r.denominator,
l.denominator * r.numerator,
).simplify();
}
// handle (k * sqrt(X)) / d 约分
if (l is MulExpr &&
l.left is IntExpr &&
l.right is SqrtExpr &&
r is IntExpr) {
int coeff = (l.left as IntExpr).value;
int denom = r.value;
int g = _gcd(coeff.abs(), denom.abs());
return MulExpr(
IntExpr(coeff ~/ g),
DivExpr(l.right, IntExpr(denom ~/ g)).evaluate(),
).evaluate();
}
return DivExpr(l, r);
}
@override
String toString() => "($left / $right)";
}
// === SqrtExpr.evaluate ===
class SqrtExpr extends Expr {
final Expr inner;
SqrtExpr(this.inner);
@override
Expr simplify() {
var i = inner.simplify();
if (i is IntExpr) {
int n = i.value;
int root = sqrt(n).floor();
if (root * root == n) {
return IntExpr(root); // 完全平方数
}
// 尝试拆分 sqrt比如 sqrt(8) = 2*sqrt(2)
for (int k = root; k > 1; k--) {
if (n % (k * k) == 0) {
return MulExpr(
IntExpr(k),
SqrtExpr(IntExpr(n ~/ (k * k))),
).simplify();
}
}
}
return SqrtExpr(i);
}
@override
Expr evaluate() {
var i = inner.evaluate();
if (i is IntExpr) {
int n = i.value;
int root = sqrt(n).floor();
if (root * root == n) return IntExpr(root);
// 拆平方因子并返回 k * sqrt(remain)
for (int k = root; k > 1; k--) {
if (n % (k * k) == 0) {
return MulExpr(
IntExpr(k),
SqrtExpr(IntExpr(n ~/ (k * k))),
).evaluate();
}
}
}
return SqrtExpr(i);
}
@override
String toString() => "sqrt($inner)";
}
// === CosExpr ===
class CosExpr extends Expr {
final Expr inner;
CosExpr(this.inner);
@override
Expr simplify() => CosExpr(inner.simplify());
@override
Expr evaluate() {
var i = inner.evaluate();
if (i is IntExpr) {
return DoubleExpr(cos(i.value.toDouble()));
}
if (i is FractionExpr) {
return DoubleExpr(cos(i.numerator / i.denominator));
}
if (i is DoubleExpr) {
return DoubleExpr(cos(i.value));
}
return CosExpr(i);
}
@override
String toString() => "cos($inner)";
}
// === SinExpr ===
class SinExpr extends Expr {
final Expr inner;
SinExpr(this.inner);
@override
Expr simplify() => SinExpr(inner.simplify());
@override
Expr evaluate() {
var i = inner.evaluate();
if (i is IntExpr) {
return DoubleExpr(sin(i.value.toDouble()));
}
if (i is FractionExpr) {
return DoubleExpr(sin(i.numerator / i.denominator));
}
if (i is DoubleExpr) {
return DoubleExpr(sin(i.value));
}
return SinExpr(i);
}
@override
String toString() => "sin($inner)";
}
// === TanExpr ===
class TanExpr extends Expr {
final Expr inner;
TanExpr(this.inner);
@override
Expr simplify() => TanExpr(inner.simplify());
@override
Expr evaluate() {
var i = inner.evaluate();
if (i is IntExpr) {
return DoubleExpr(tan(i.value.toDouble()));
}
if (i is FractionExpr) {
return DoubleExpr(tan(i.numerator / i.denominator));
}
if (i is DoubleExpr) {
return DoubleExpr(tan(i.value));
}
return TanExpr(i);
}
@override
String toString() => "tan($inner)";
}
// === 辅助:识别 a * sqrt(X) 形式 ===
class _SqrtTerm {
final int coef;
final Expr inner;
_SqrtTerm(this.coef, this.inner);
}
_SqrtTerm? _asSqrtTerm(Expr e) {
if (e is SqrtExpr) return _SqrtTerm(1, e.inner);
if (e is MulExpr) {
// 可能为 Int * Sqrt or Sqrt * Int
if (e.left is IntExpr && e.right is SqrtExpr) {
return _SqrtTerm((e.left as IntExpr).value, (e.right as SqrtExpr).inner);
}
if (e.right is IntExpr && e.left is SqrtExpr) {
return _SqrtTerm((e.right as IntExpr).value, (e.left as SqrtExpr).inner);
}
}
return null;
}
/// 辗转相除法求 gcd
int _gcd(int a, int b) => b == 0 ? a : _gcd(b, a % b);

111
lib/parser.dart Normal file
View File

@@ -0,0 +1,111 @@
import 'package:simple_math_calc/calculator.dart';
class Parser {
final String input;
int pos = 0;
Parser(this.input);
bool get isEnd => pos >= input.length;
String get current => isEnd ? '' : input[pos];
void eat() => pos++;
void skipSpaces() {
while (!isEnd && input[pos] == ' ') {
eat();
}
}
Expr parse() => parseAdd();
Expr parseAdd() {
var expr = parseMul();
skipSpaces();
while (!isEnd && (current == '+' || current == '-')) {
var op = current;
eat();
var right = parseMul();
expr = op == '+' ? AddExpr(expr, right) : SubExpr(expr, right);
skipSpaces();
}
return expr;
}
Expr parseMul() {
var expr = parseAtom();
skipSpaces();
while (!isEnd && (current == '*' || current == '/')) {
var op = current;
eat();
var right = parseAtom();
if (op == '*') {
expr = MulExpr(expr, right);
} else {
expr = DivExpr(expr, right);
}
skipSpaces();
}
return expr;
}
Expr parseAtom() {
skipSpaces();
if (current == '(') {
eat();
var expr = parse();
if (current != ')') throw Exception("缺少 )");
eat();
return expr;
}
if (input.startsWith("sqrt", pos)) {
pos += 4;
if (current != '(') throw Exception("sqrt 缺少 (");
eat();
var inner = parse();
if (current != ')') throw Exception("sqrt 缺少 )");
eat();
return SqrtExpr(inner);
}
if (input.startsWith("cos", pos)) {
pos += 3;
if (current != '(') throw Exception("cos 缺少 (");
eat();
var inner = parse();
if (current != ')') throw Exception("cos 缺少 )");
eat();
return CosExpr(inner);
}
if (input.startsWith("sin", pos)) {
pos += 3;
if (current != '(') throw Exception("sin 缺少 (");
eat();
var inner = parse();
if (current != ')') throw Exception("sin 缺少 )");
eat();
return SinExpr(inner);
}
if (input.startsWith("tan", pos)) {
pos += 3;
if (current != '(') throw Exception("tan 缺少 (");
eat();
var inner = parse();
if (current != ')') throw Exception("tan 缺少 )");
eat();
return TanExpr(inner);
}
// 解析整数
var buf = '';
while (!isEnd && RegExp(r'\d').hasMatch(current)) {
buf += current;
eat();
}
if (buf.isEmpty) throw Exception("无法解析: $current");
return IntExpr(int.parse(buf));
}
}

View File

@@ -1,9 +1,9 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:latext/latext.dart';
import 'package:simple_math_calc/models/calculation_step.dart';
import 'package:simple_math_calc/solver.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:math_expressions/math_expressions.dart' as math_expressions;
import 'dart:math';
class CalculatorHomePage extends StatefulWidget {
@@ -20,25 +20,141 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
CalculationResult? _result;
bool _isLoading = false;
bool _isInputFocused = false;
double _zoomFactor = 1.0;
@override
void initState() {
super.initState();
_focusNode = FocusNode();
_focusNode.addListener(() {
setState(() {
_isInputFocused = _focusNode.hasFocus;
});
});
_controller.addListener(_onTextChanged);
}
@override
void dispose() {
_controller.removeListener(_onTextChanged);
_focusNode.dispose();
super.dispose();
}
void _onTextChanged() {
setState(() {});
}
/// 生成函数图表的点
List<FlSpot> _generatePlotPoints(String expression, double zoomFactor) {
try {
// 如果是方程,取左边作为函数
String functionExpr = expression;
if (expression.contains('=')) {
functionExpr = expression.split('=')[0].trim();
}
// 如果表达式不包含 x返回空列表
if (!functionExpr.contains('x') && !functionExpr.contains('X')) {
return [];
}
// 预处理表达式,确保格式正确
functionExpr = functionExpr.replaceAll(' ', '');
// 在数字和变量之间插入乘号
functionExpr = functionExpr.replaceAllMapped(
RegExp(r'(\d)([a-zA-Z])'),
(match) => '${match.group(1)}*${match.group(2)}',
);
// 在变量和数字之间插入乘号 (如 x2 -> x*2)
functionExpr = functionExpr.replaceAllMapped(
RegExp(r'([a-zA-Z])(\d)'),
(match) => '${match.group(1)}*${match.group(2)}',
);
// 解析表达式
final parser = math_expressions.ShuntingYardParser();
final expr = parser.parse(functionExpr);
// 创建变量 x
final x = math_expressions.Variable('x');
// 根据缩放因子动态调整范围和步长
final range = 10.0 * zoomFactor;
final step = max(0.05, 0.2 / zoomFactor); // 缩放时步长更小,放大时步长更大
// 生成点
List<FlSpot> points = [];
for (double i = -range; i <= range; i += step) {
try {
final context = math_expressions.ContextModel()
..bindVariable(x, math_expressions.Number(i));
final evaluator = math_expressions.RealEvaluator(context);
final y = evaluator.evaluate(expr);
if (y.isFinite && !y.isNaN) {
points.add(FlSpot(i, y.toDouble()));
}
} catch (e) {
// 跳过无法计算的点
continue;
}
}
// 如果没有足够的点,返回空列表
if (points.length < 2) {
debugPrint('Generated ${points.length} dots');
return [];
}
// 排序点按 x 值
points.sort((a, b) => a.x.compareTo(b.x));
debugPrint(
'Generated ${points.length} dots with zoom factor $zoomFactor',
);
return points;
} catch (e) {
debugPrint('Error generating plot points: $e');
return [];
}
}
/// 计算图表的数据范围
({double minX, double maxX, double minY, double maxY}) _calculateChartBounds(
List<FlSpot> points,
double zoomFactor,
) {
if (points.isEmpty) {
return (
minX: -10 * zoomFactor,
maxX: 10 * zoomFactor,
minY: -50 * zoomFactor,
maxY: 50 * zoomFactor,
);
}
double minX = points.first.x;
double maxX = points.first.x;
double minY = points.first.y;
double maxY = points.first.y;
for (final point in points) {
minX = min(minX, point.x);
maxX = max(maxX, point.x);
minY = min(minY, point.y);
maxY = max(maxY, point.y);
}
// 添加边距
final xPadding = (maxX - minX) * 0.1;
final yPadding = (maxY - minY) * 0.1;
return (
minX: minX - xPadding,
maxX: maxX + xPadding,
minY: minY - yPadding,
maxY: maxY + yPadding,
);
}
void _solveEquation() {
if (_controller.text.isEmpty) {
return;
@@ -69,21 +185,23 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
}
}
void _insertSymbol(String symbol) {
final text = _controller.text;
final selection = _controller.selection;
final newText = text.replaceRange(selection.start, selection.end, symbol);
_controller.text = newText;
_controller.selection = TextSelection.collapsed(
offset: selection.start + symbol.length,
);
void _zoomIn() {
setState(() {
_zoomFactor = (_zoomFactor * 0.8).clamp(0.1, 10.0);
});
}
void _zoomOut() {
setState(() {
_zoomFactor = (_zoomFactor * 1.25).clamp(0.1, 10.0);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('方程与表达式计算器'),
title: const Text('计算器'),
centerTitle: false,
leading: const Icon(Icons.calculate_outlined),
),
@@ -105,12 +223,10 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
floatingLabelAlignment: FloatingLabelAlignment.center,
hintText: '例如: 2x^2 - 8x + 6 = 0',
),
keyboardType: kIsWeb
? TextInputType.numberWithOptions(
keyboardType: TextInputType.numberWithOptions(
signed: true,
decimal: true,
)
: TextInputType.number,
),
onSubmitted: (_) => _solveEquation(),
),
),
@@ -128,7 +244,6 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
? const Center(child: Text('请输入方程开始计算'))
: buildResultView(_result!),
),
if (_isInputFocused) _buildToolbar(),
],
),
);
@@ -239,155 +354,107 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
),
),
),
],
);
}
Widget _buildToolbar() {
return Material(
elevation: 8,
const SizedBox(height: 16),
Card(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8),
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
spacing: 8,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Tooltip(
message: '左括号',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('('),
child: Text('(', style: GoogleFonts.robotoMono()),
Padding(
padding: const EdgeInsets.only(left: 4),
child: Text(
'函数图像',
style: Theme.of(context).textTheme.titleMedium,
),
),
),
Expanded(
child: Tooltip(
message: '右括号',
child: FilledButton.tonal(
onPressed: () => _insertSymbol(')'),
child: Text(')', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '幂符号',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('^'),
child: Text('^', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '平方',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('^2'),
child: Text('²', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '未知数',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('x'),
child: Text('x', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '未知数二号',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('y'),
child: Text('y', style: GoogleFonts.robotoMono()),
),
),
),
],
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
spacing: 8,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Tooltip(
message: '加法',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('+'),
child: Text('+', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '减法',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('-'),
child: Text('-', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '乘法',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('*'),
child: Text('*', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '除法',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('/'),
child: Text('/', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '小数点',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('.'),
child: Text('.', style: GoogleFonts.robotoMono()),
),
),
),
Expanded(
child: Tooltip(
message: '等于号',
child: FilledButton.tonal(
onPressed: () => _insertSymbol('='),
child: Text('=', style: GoogleFonts.robotoMono()),
),
),
),
],
),
if (!kIsWeb) const SizedBox(height: 8),
if (!kIsWeb)
Row(
children: [
Expanded(
child: FilledButton.icon(
icon: const Icon(Icons.keyboard_hide),
onPressed: () => _focusNode.unfocus(),
label: Text('收起键盘'),
IconButton(
onPressed: _zoomIn,
icon: Icon(Icons.zoom_in),
tooltip: '放大',
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
),
IconButton(
onPressed: _zoomOut,
icon: Icon(Icons.zoom_out),
tooltip: '缩小',
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
),
],
),
],
),
const SizedBox(height: 24),
SizedBox(
height: 340,
child: Builder(
builder: (context) {
final points = _generatePlotPoints(
_controller.text,
_zoomFactor,
);
final bounds = _calculateChartBounds(points, _zoomFactor);
return LineChart(
LineChartData(
gridData: FlGridData(show: true),
titlesData: FlTitlesData(
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 40,
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 30,
),
),
topTitles: AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
rightTitles: AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
),
borderData: FlBorderData(
show: true,
border: Border.all(
color: Theme.of(context).colorScheme.outline,
),
),
lineBarsData: [
LineChartBarData(
spots: points,
isCurved: true,
color: Theme.of(context).colorScheme.primary,
barWidth: 3,
belowBarData: BarAreaData(show: false),
dotData: FlDotData(show: false),
),
],
minX: bounds.minX,
maxX: bounds.maxX,
minY: bounds.minY,
maxY: bounds.maxY,
),
);
},
),
),
],
),
),
),
],
);
}
}

View File

@@ -1,7 +1,8 @@
import 'dart:math';
import 'package:flutter/foundation.dart'; // For kDebugMode
import 'package:math_expressions/math_expressions.dart';
import 'package:rational/rational.dart';
import 'models/calculation_step.dart';
import 'calculator.dart';
import 'parser.dart';
/// 帮助解析一元一次方程 ax+b=cx+d 的辅助类
class LinearEquationParts {
@@ -42,9 +43,6 @@ class SolverService {
try {
return _solveSimpleExpression(input); // 使用原始输入以保留运算符
} catch (e) {
if (kDebugMode) {
print(e);
}
throw Exception('无法识别的格式。请检查您的方程或表达式。');
}
}
@@ -75,9 +73,30 @@ class SolverService {
// 预处理输入,将三角函数的参数从度转换为弧度
String processedInput = _convertTrigToRadians(input);
GrammarParser p = GrammarParser();
Expression exp = p.parse(processedInput);
final result = RealEvaluator().evaluate(exp).toDouble();
try {
// 使用自定义解析器解析表达式
final parser = Parser(processedInput);
final expr = parser.parse();
// 对表达式进行求值
final evaluatedExpr = expr.evaluate();
// 获取数值结果 - 需要正确进行类型转换
double result;
if (evaluatedExpr is IntExpr) {
result = evaluatedExpr.value.toDouble();
} else if (evaluatedExpr is DoubleExpr) {
result = evaluatedExpr.value;
} else if (evaluatedExpr is FractionExpr) {
result = evaluatedExpr.numerator / evaluatedExpr.denominator;
} else {
// 如果无法完全求值为数值,尝试简化并转换为字符串
final simplified = evaluatedExpr.simplify();
return CalculationResult(
steps: steps,
finalAnswer: '\$\$${simplified.toString()}\$\$',
);
}
// 尝试将结果格式化为几倍根号的形式
final formattedResult = _formatSqrtResult(result);
@@ -86,6 +105,9 @@ class SolverService {
steps: steps,
finalAnswer: '\$\$$formattedResult\$\$',
);
} catch (e) {
throw Exception('无法解析表达式: $input');
}
}
/// 2. 求解一元一次方程
@@ -103,8 +125,8 @@ class SolverService {
final parts = _parseLinearEquation(input);
final a = parts.a, b = parts.b, c = parts.c, d = parts.d;
final newA = a - c;
final newD = d - b;
final newA = _rationalFromDouble(a) - _rationalFromDouble(c);
final newD = _rationalFromDouble(d) - _rationalFromDouble(b);
steps.add(
CalculationStep(
@@ -121,14 +143,15 @@ class SolverService {
stepNumber: 2,
title: '合并同类项',
explanation: '合并等式两边的项。',
formula: '\$\$${newA}x = $newD\$\$',
formula:
'\$\$${newA.toDouble().toStringAsFixed(4)}x = ${newD.toDouble().toStringAsFixed(4)}\$\$',
),
);
if (newA == 0) {
if (newA == Rational.zero) {
return CalculationResult(
steps: steps,
finalAnswer: newD == 0 ? '有无穷多解' : '无解',
finalAnswer: newD == Rational.zero ? '有无穷多解' : '无解',
);
}
@@ -152,9 +175,29 @@ class SolverService {
final eqParts = input.split('=');
if (eqParts.length != 2) throw Exception("方程格式错误,应包含一个 '='。");
// Keep original equation for display
final originalEquation = _formatOriginalEquation(input);
// Parse coefficients symbolically
final leftCoeffsSymbolic = _parsePolynomialSymbolic(eqParts[0]);
final rightCoeffsSymbolic = _parsePolynomialSymbolic(eqParts[1]);
final aSymbolic = _subtractCoefficients(
leftCoeffsSymbolic[2] ?? '0',
rightCoeffsSymbolic[2] ?? '0',
);
final bSymbolic = _subtractCoefficients(
leftCoeffsSymbolic[1] ?? '0',
rightCoeffsSymbolic[1] ?? '0',
);
final cSymbolic = _subtractCoefficients(
leftCoeffsSymbolic[0] ?? '0',
rightCoeffsSymbolic[0] ?? '0',
);
// Also get numeric values for calculations
final leftCoeffs = _parsePolynomial(eqParts[0]);
final rightCoeffs = _parsePolynomial(eqParts[1]);
final a = (leftCoeffs[2] ?? 0) - (rightCoeffs[2] ?? 0);
final b = (leftCoeffs[1] ?? 0) - (rightCoeffs[1] ?? 0);
final c = (leftCoeffs[0] ?? 0) - (rightCoeffs[0] ?? 0);
@@ -168,8 +211,7 @@ class SolverService {
stepNumber: 1,
title: '整理方程',
explanation: r'将方程整理成标准形式 $ax^2+bx+c=0$。',
formula:
'\$\$${a}x^2 ${b >= 0 ? '+' : ''} ${b}x ${c >= 0 ? '+' : ''} $c = 0\$\$',
formula: originalEquation,
),
);
@@ -213,36 +255,46 @@ class SolverService {
),
);
final delta = b * b - 4 * a * c;
// Calculate delta symbolically
final deltaSymbolic = _calculateDeltaSymbolic(
aSymbolic,
bSymbolic,
cSymbolic,
);
final delta =
_rationalFromDouble(b).pow(2) -
Rational.fromInt(4) * _rationalFromDouble(a) * _rationalFromDouble(c);
steps.add(
CalculationStep(
stepNumber: 3,
title: '计算判别式 (Delta)',
explanation:
'\$\$\\Delta = b^2 - 4ac = ($b)^2 - 4 \\cdot ($a) \\cdot ($c) = $delta\$\$',
formula: '\$\$\\Delta = $delta\$\$',
explanation: '\$\$\\Delta = b^2 - 4ac = $deltaSymbolic\$\$',
formula:
'\$\$\\Delta = $deltaSymbolic = ${delta.toDouble().toStringAsFixed(4)}\$\$',
),
);
if (delta > 0) {
final x1 = (-b + sqrt(delta)) / (2 * a);
final x2 = (-b - sqrt(delta)) / (2 * a);
final deltaDouble = delta.toDouble();
if (deltaDouble > 0) {
// Pass delta directly to maintain precision
final x1Expr = _formatQuadraticRoot(-b, delta, 2 * a, true);
final x2Expr = _formatQuadraticRoot(-b, delta, 2 * a, false);
steps.add(
CalculationStep(
stepNumber: 4,
title: '应用求根公式',
explanation:
r'因为 $\Delta > 0$,方程有两个不相等的实数根。公式: $x = \frac{-b \pm \sqrt{\Delta}}{2a}$。',
formula:
'\$\$x_1 = ${x1.toStringAsFixed(4)}, \\quad x_2 = ${x2.toStringAsFixed(4)}\$\$',
formula: '\$\$x_1 = $x1Expr, \\quad x_2 = $x2Expr\$\$',
),
);
return CalculationResult(
steps: steps,
finalAnswer:
'\$\$x_1 = ${x1.toStringAsFixed(4)}, \\quad x_2 = ${x2.toStringAsFixed(4)}\$\$',
finalAnswer: '\$\$x_1 = $x1Expr, \\quad x_2 = $x2Expr\$\$',
);
} else if (delta == 0) {
} else if (deltaDouble == 0) {
final x = -b / (2 * a);
steps.add(
CalculationStep(
@@ -266,9 +318,11 @@ class SolverService {
),
);
final sqrtDelta = sqrt(-delta);
// For complex roots, we need to handle -delta
final negDelta = -delta;
final sqrtNegDeltaStr = _formatSqrtFromRational(negDelta);
final realPart = -b / (2 * a);
final imagPart = sqrtDelta / (2 * a);
final imagPartExpr = _formatImaginaryPart(sqrtNegDeltaStr, 2 * a);
steps.add(
CalculationStep(
@@ -282,7 +336,7 @@ class SolverService {
return CalculationResult(
steps: steps,
finalAnswer:
'\$\$x_1 = ${realPart.toStringAsFixed(4)} + ${imagPart.toStringAsFixed(4)}i, \\quad x_2 = ${realPart.toStringAsFixed(4)} - ${imagPart.toStringAsFixed(4)}i\$\$',
'\$\$x_1 = ${realPart.toStringAsFixed(4)} + $imagPartExpr, \\quad x_2 = ${realPart.toStringAsFixed(4)} - $imagPartExpr\$\$',
);
}
}
@@ -316,16 +370,23 @@ ${a2}x ${b2 >= 0 ? '+' : ''} ${b2}y = $c2 & (2)
),
);
final det = a1 * b2 - a2 * b1;
if (det == 0) {
final det =
_rationalFromDouble(a1) * _rationalFromDouble(b2) -
_rationalFromDouble(a2) * _rationalFromDouble(b1);
if (det == Rational.zero) {
final infiniteCheck =
_rationalFromDouble(a1) * _rationalFromDouble(c2) -
_rationalFromDouble(a2) * _rationalFromDouble(c1);
return CalculationResult(
steps: steps,
finalAnswer: a1 * c2 - a2 * c1 == 0 ? '有无穷多解' : '无解',
finalAnswer: infiniteCheck == Rational.zero ? '有无穷多解' : '无解',
);
}
final newA1 = a1 * b2, newC1 = c1 * b2;
final newA2 = a2 * b1, newC2 = c2 * b1;
final newA1 = _rationalFromDouble(a1) * _rationalFromDouble(b2);
final newC1 = _rationalFromDouble(c1) * _rationalFromDouble(b2);
final newA2 = _rationalFromDouble(a2) * _rationalFromDouble(b1);
final newC2 = _rationalFromDouble(c2) * _rationalFromDouble(b1);
steps.add(
CalculationStep(
@@ -336,8 +397,8 @@ ${a2}x ${b2 >= 0 ? '+' : ''} ${b2}y = $c2 & (2)
'''
\$\$
\\begin{cases}
${newA1}x ${b1 * b2 >= 0 ? '+' : ''} ${b1 * b2}y = $newC1 & (3) \\\\
${newA2}x ${b1 * b2 >= 0 ? '+' : ''} ${b1 * b2}y = $newC2 & (4)
${newA1.toDouble().toStringAsFixed(2)}x ${b1 * b2 >= 0 ? '+' : ''} ${(b1 * b2).toStringAsFixed(2)}y = ${newC1.toDouble().toStringAsFixed(2)} & (3) \\\\
${newA2.toDouble().toStringAsFixed(2)}x ${b1 * b2 >= 0 ? '+' : ''} ${(b1 * b2).toStringAsFixed(2)}y = ${newC2.toDouble().toStringAsFixed(2)} & (4)
\\end{cases}
\$\$
''',
@@ -353,7 +414,7 @@ ${newA2}x ${b1 * b2 >= 0 ? '+' : ''} ${b1 * b2}y = $newC2 & (4)
title: '相减',
explanation: '将方程(3)减去方程(4),得到一个只含 x 的方程。',
formula:
'\$\$($newA1 - $newA2)x = $newC1 - $newC2 \\Rightarrow ${xCoeff}x = $constCoeff\$\$',
'\$\$(${newA1.toDouble().toStringAsFixed(2)} - ${newA2.toDouble().toStringAsFixed(2)})x = ${newC1.toDouble().toStringAsFixed(2)} - ${newC2.toDouble().toStringAsFixed(2)} \\Rightarrow ${xCoeff.toDouble().toStringAsFixed(2)}x = ${constCoeff.toDouble().toStringAsFixed(2)}\$\$',
),
);
@@ -369,21 +430,21 @@ ${newA2}x ${b1 * b2 >= 0 ? '+' : ''} ${b1 * b2}y = $newC2 & (4)
if (b1.abs() < 1e-9) {
final yCoeff = b2;
final yConst = c2 - a2 * x;
final yConst = c2 - a2 * x.toDouble();
final y = yConst / yCoeff;
steps.add(
CalculationStep(
stepNumber: 4,
title: '回代求解 y',
explanation: '将 x = $x 代入原方程(2)中。',
explanation: '将 x = ${x.toDouble().toStringAsFixed(4)} 代入原方程(2)中。',
formula:
'''
\$\$
\\begin{aligned}
$a2($x) + ${b2}y &= $c2 \\\\
${a2 * x} + ${b2}y &= $c2 \\\\
${b2}y &= $c2 - ${a2 * x} \\\\
${b2}y &= ${c2 - a2 * x}
$a2(${x.toDouble().toStringAsFixed(4)}) + ${b2}y &= $c2 \\\\
${a2 * x.toDouble()} + ${b2}y &= $c2 \\\\
${b2}y &= $c2 - ${a2 * x.toDouble()} \\\\
${b2}y &= ${c2 - a2 * x.toDouble()}
\\end{aligned}
\$\$
''',
@@ -394,30 +455,31 @@ ${b2}y &= ${c2 - a2 * x}
stepNumber: 5,
title: '解出 y',
explanation: '求解得到 y 的值。',
formula: '\$\$y = $y\$\$',
formula: '\$\$y = ${y.toStringAsFixed(4)}\$\$',
),
);
return CalculationResult(
steps: steps,
finalAnswer: '\$\$x = $x, \\quad y = $y\$\$',
finalAnswer:
'\$\$x = ${x.toDouble().toStringAsFixed(4)}, \\quad y = ${y.toStringAsFixed(4)}\$\$',
);
} else {
final yCoeff = b1;
final yConst = c1 - a1 * x;
final yConst = c1 - a1 * x.toDouble();
final y = yConst / yCoeff;
steps.add(
CalculationStep(
stepNumber: 4,
title: '回代求解 y',
explanation: '将 x = $x 代入原方程(1)中。',
explanation: '将 x = ${x.toDouble().toStringAsFixed(4)} 代入原方程(1)中。',
formula:
'''
\$\$
\\begin{aligned}
$a1($x) + ${b1}y &= $c1 \\\\
${a1 * x} + ${b1}y &= $c1 \\\\
${b1}y &= $c1 - ${a1 * x} \\\\
${b1}y &= ${c1 - a1 * x}
$a1(${x.toDouble().toStringAsFixed(4)}) + ${b1}y &= $c1 \\\\
${a1 * x.toDouble()} + ${b1}y &= $c1 \\\\
${b1}y &= $c1 - ${a1 * x.toDouble()} \\\\
${b1}y &= ${c1 - a1 * x.toDouble()}
\\end{aligned}
\$\$
''',
@@ -428,12 +490,13 @@ ${b1}y &= ${c1 - a1 * x}
stepNumber: 5,
title: '解出 y',
explanation: '求解得到 y 的值。',
formula: '\$\$y = $y\$\$',
formula: '\$\$y = ${y.toStringAsFixed(4)}\$\$',
),
);
return CalculationResult(
steps: steps,
finalAnswer: '\$\$x = $x, \\quad y = $y\$\$',
finalAnswer:
'\$\$x = ${x.toDouble().toStringAsFixed(4)}, \\quad y = ${y.toStringAsFixed(4)}\$\$',
);
}
}
@@ -672,21 +735,28 @@ ${b1}y &= ${c1 - a1 * x}
if (factorMulMatch != null) {
final factor1 = factorMulMatch.group(1)!;
final factor2 = factorMulMatch.group(2)!;
print('Expanding: ($factor1) * ($factor2)');
final coeffs1 = _parsePolynomial(factor1);
final coeffs2 = _parsePolynomial(factor2);
print('Coeffs1: $coeffs1, Coeffs2: $coeffs2');
final a = coeffs1[1] ?? 0;
final b = coeffs1[0] ?? 0;
final c = coeffs2[1] ?? 0;
final d = coeffs2[0] ?? 0;
print('a=$a, b=$b, c=$c, d=$d');
final newA = a * c;
final newB = a * d + b * c;
final newC = b * d;
print('newA=$newA, newB=$newB, newC=$newC');
final expanded =
'${newA}x^2${newB >= 0 ? '+' : ''}${newB}x${newC >= 0 ? '+' : ''}$newC';
result = result.replaceFirst(factorMulMatch.group(0)!, '($expanded)');
print('Expanded result: $expanded');
result = result.replaceFirst(factorMulMatch.group(0)!, expanded);
iterationCount++;
continue;
}
@@ -720,7 +790,11 @@ ${b1}y &= ${c1 - a1 * x}
final newC = termB * factorB;
final expanded =
'${newA}x^2${newB >= 0 ? '+' : ''}${newB}x${newC >= 0 ? '+' : ''}$newC';
'${newA == 1
? ''
: newA == -1
? '-'
: newA}x^2${newB >= 0 ? '+' : ''}${newB}x${newC >= 0 ? '+' : ''}$newC';
result = result.replaceFirst(termFactorMatch.group(0)!, '($expanded)');
iterationCount++;
continue;
@@ -734,6 +808,54 @@ ${b1}y &= ${c1 - a1 * x}
throw Exception('表达式展开过于复杂,请简化输入。');
}
// 检查是否为方程(包含等号),如果是的话,将右边的常数项移到左边
if (result.contains('=')) {
final parts = result.split('=');
if (parts.length == 2) {
final leftSide = parts[0];
final rightSide = parts[1];
// 解析左边的多项式
final leftCoeffs = _parsePolynomial(leftSide);
final rightCoeffs = _parsePolynomial(rightSide);
// 计算标准形式 ax^2 + bx + c = 0 的系数
// A = B 转换为 A - B = 0所以右边的系数要取相反数
final a = (leftCoeffs[2] ?? 0) - (rightCoeffs[2] ?? 0);
final b = (leftCoeffs[1] ?? 0) - (rightCoeffs[1] ?? 0);
final c = (leftCoeffs[0] ?? 0) - (rightCoeffs[0] ?? 0);
// 构建标准形式的方程
String standardForm = '';
if (a != 0) {
standardForm +=
'${a == 1
? ''
: a == -1
? '-'
: a}x^2';
}
if (b != 0) {
standardForm += b > 0 ? '+${b}x' : '${b}x';
}
if (c != 0) {
standardForm += c > 0 ? '+$c' : '$c';
}
// 移除开头的加号
if (standardForm.startsWith('+')) {
standardForm = standardForm.substring(1);
}
// 如果所有系数都为0则方程恒成立
if (standardForm.isEmpty) {
standardForm = '0';
}
result = '$standardForm=0';
}
}
return result;
}
@@ -754,13 +876,24 @@ ${b1}y &= ${c1 - a1 * x}
Map<int, double> _parsePolynomial(String side) {
final coeffs = <int, double>{};
// 如果输入包含括号,去掉括号
var cleanSide = side;
if (cleanSide.startsWith('(') && cleanSide.endsWith(')')) {
cleanSide = cleanSide.substring(1, cleanSide.length - 1);
}
// 扩展模式以支持 sqrt 函数
final pattern = RegExp(
r'([+-]?(?:\d*\.?\d*|sqrt\(\d+\)))x(?:\^(\d+))?|([+-]?(?:\d*\.?\d*|sqrt\(\d+\)))',
);
var s = side.startsWith('+') || side.startsWith('-') ? side : '+$side';
var s = cleanSide.startsWith('+') || cleanSide.startsWith('-')
? cleanSide
: '+$cleanSide';
for (final match in pattern.allMatches(s)) {
if (match.group(0)!.isEmpty) continue; // Skip empty matches
if (match.group(3) != null) {
// 常数项
final constStr = match.group(3)!;
@@ -851,26 +984,31 @@ ${b1}y &= ${c1 - a1 * x}
if (a == 0) return null;
int ac = a * c;
int absAc = ac.abs();
// Try all divisors of abs(ac) and consider both positive and negative factors
for (int d = 1; d <= sqrt(absAc).toInt(); d++) {
if (absAc % d == 0) {
int d1 = d;
int d2 = absAc ~/ d;
List<int> signs1 = ac >= 0 ? [1, -1] : [1, -1];
List<int> signs2 = ac >= 0 ? [1, -1] : [1, -1];
for (int s1 in signs1) {
for (int s2 in signs2) {
int m = s1 * d1;
int n = s2 * d2;
if (check(m, n, b)) return formatFactor(m, n, a);
m = s1 * d1;
n = s2 * (-d2);
if (check(m, n, b)) return formatFactor(m, n, a);
m = s1 * (-d1);
n = s2 * d2;
if (check(m, n, b)) return formatFactor(m, n, a);
m = s1 * (-d1);
n = s2 * (-d2);
if (check(m, n, b)) return formatFactor(m, n, a);
// Try all sign combinations for the factors
// We need m * n = ac and m + n = b
List<int> signCombinations = [1, -1];
for (int sign1 in signCombinations) {
for (int sign2 in signCombinations) {
int m = sign1 * d1;
int n = sign2 * d2;
if (m + n == b && m * n == ac) {
return formatFactor(m, n, a);
}
// Also try the swapped version
m = sign1 * d2;
n = sign2 * d1;
if (m + n == b && m * n == ac) {
return formatFactor(m, n, a);
}
}
}
}
@@ -940,4 +1078,396 @@ ${b1}y &= ${c1 - a1 * x}
}
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
/// 格式化 Rational 值的平方根表达式,保持符号形式
String _formatSqrtFromRational(Rational value) {
if (value == Rational.zero) return '0';
// 处理负数(用于复数根)
if (value < Rational.zero) {
return '\\sqrt{${(-value).toBigInt()}}';
}
// 尝试将 Rational 转换为完全平方数的形式
// 例如: 4/9 -> 2/3, 9/4 -> 3/2, 25/16 -> 5/4 等
// 首先简化分数
final simplified = value;
// 检查分子和分母是否都是完全平方数
final numerator = simplified.numerator;
final denominator = simplified.denominator;
// 寻找分子和分母的平方根因子
BigInt sqrtNumerator = _findSquareRootFactor(numerator);
BigInt sqrtDenominator = _findSquareRootFactor(denominator);
// 计算剩余的分子和分母
final remainingNumerator = numerator ~/ (sqrtNumerator * sqrtNumerator);
final remainingDenominator =
denominator ~/ (sqrtDenominator * sqrtDenominator);
// 构建结果
String result = '';
// 处理系数部分
if (sqrtNumerator > BigInt.one || sqrtDenominator > BigInt.one) {
if (sqrtNumerator > sqrtDenominator) {
final coeff = sqrtNumerator ~/ sqrtDenominator;
if (coeff > BigInt.one) {
result += '$coeff';
}
} else if (sqrtDenominator > sqrtNumerator) {
// 这会导致分母,需要用分数表示
final coeffNum = sqrtNumerator;
final coeffDen = sqrtDenominator;
if (coeffNum == BigInt.one) {
result += '\\frac{1}{$coeffDen}';
} else {
result += '\\frac{$coeffNum}{$coeffDen}';
}
}
}
// 处理根号部分
if (remainingNumerator == BigInt.one &&
remainingDenominator == BigInt.one) {
// 没有根号部分
if (result.isEmpty) {
return '1';
}
} else if (remainingNumerator == remainingDenominator) {
// 根号部分约分后为1
if (result.isEmpty) {
return '1';
}
} else {
// 需要根号
String sqrtContent = '';
if (remainingDenominator == BigInt.one) {
sqrtContent = '$remainingNumerator';
} else {
sqrtContent = '\\frac{$remainingNumerator}{$remainingDenominator}';
}
if (result.isEmpty) {
result = '\\sqrt{$sqrtContent}';
} else {
result += '\\sqrt{$sqrtContent}';
}
}
return result.isEmpty ? '1' : result;
}
/// 寻找一个大整数的平方根因子
BigInt _findSquareRootFactor(BigInt n) {
if (n <= BigInt.one) return BigInt.one;
BigInt factor = BigInt.one;
BigInt i = BigInt.two;
while (i * i <= n) {
BigInt count = BigInt.zero;
while (n % (i * i) == BigInt.zero) {
n = n ~/ (i * i);
count += BigInt.one;
}
if (count > BigInt.zero) {
factor = factor * i;
}
i += BigInt.one;
}
return factor;
}
/// 格式化二次方程的根:(-b ± sqrt(delta)) / (2a)
String _formatQuadraticRoot(
double b,
Rational delta,
double denominator,
bool isPlus,
) {
final denomInt = denominator.toInt();
final denomStr = denominator == 2 ? '2' : denominator.toString();
// Format sqrt(delta) symbolically using the Rational value
final sqrtExpr = _formatSqrtFromRational(delta);
if (b == 0) {
// 简化为 ±sqrt(delta)/denominator
if (denominator == 2) {
return isPlus ? '\\frac{$sqrtExpr}{2}' : '-\\frac{$sqrtExpr}{2}';
} else {
return isPlus
? '\\frac{$sqrtExpr}{$denomStr}'
: '-\\frac{$sqrtExpr}{$denomStr}';
}
} else {
// 完整的表达式:(-b ± sqrt(delta))/denominator
final bInt = b.toInt();
// Check if b is divisible by denominator for simplification
if (bInt % denomInt == 0) {
// Can simplify: b/denominator becomes integer
final simplifiedB = bInt ~/ denomInt;
if (simplifiedB == 0) {
// Just the sqrt part with correct sign
return isPlus ? '$sqrtExpr' : '-$sqrtExpr';
} else if (simplifiedB == 1) {
// +1 * sqrt part
return isPlus ? '1 + $sqrtExpr' : '1 - $sqrtExpr';
} else if (simplifiedB == -1) {
// -1 * sqrt part
return isPlus ? '-1 + $sqrtExpr' : '-1 - $sqrtExpr';
} else if (simplifiedB > 0) {
// Positive coefficient
return isPlus
? '$simplifiedB + $sqrtExpr'
: '$simplifiedB - $sqrtExpr';
} else {
// Negative coefficient
final absB = (-simplifiedB).toString();
return isPlus ? '-$absB + $sqrtExpr' : '-$absB - $sqrtExpr';
}
} else {
// Cannot simplify, use fraction form
final bStr = b > 0 ? '${bInt}' : '(${bInt})';
final signStr = isPlus ? '+' : '-';
final numerator = b > 0
? '-$bStr $signStr $sqrtExpr'
: '(${bInt}) $signStr $sqrtExpr';
if (denominator == 2) {
return '\\frac{$numerator}{2}';
} else {
return '\\frac{$numerator}{$denomStr}';
}
}
}
}
/// 格式化复数根的虚部sqrt(-delta)/(2a)
String _formatImaginaryPart(String sqrtExpr, double denominator) {
final denomStr = denominator == 2 ? '2' : denominator.toString();
if (denominator == 2) {
return '\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{2}i';
} else {
return '\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{$denomStr}i';
}
}
/// 格式化原始方程,保持符号形式
String _formatOriginalEquation(String input) {
// Simply return the original equation with proper LaTeX formatting
// This avoids complex parsing issues and preserves the original symbolic form
String result = input.replaceAll(' ', '');
// 确保方程格式正确
if (!result.contains('=')) {
result = '$result=0';
}
// Replace sqrt with LaTeX format
result = result.replaceAll('sqrt(', '\\sqrt{');
result = result.replaceAll(')', '}');
return '\$\$$result\$\$';
}
/// 解析多项式,保持符号形式
Map<int, String> _parsePolynomialSymbolic(String side) {
final coeffs = <int, String>{};
// Use a simpler approach: split by terms and parse each term individually
var s = side.replaceAll(' ', ''); // Remove spaces
if (!s.startsWith('+') && !s.startsWith('-')) {
s = '+$s';
}
// Split by + and - but be more careful about parentheses and functions
final terms = <String>[];
int start = 0;
int parenDepth = 0;
for (int i = 0; i < s.length; i++) {
final char = s[i];
if (char == '(') {
parenDepth++;
} else if (char == ')') {
parenDepth--;
}
// Only split on + or - when not inside parentheses
if (parenDepth == 0 && (char == '+' || char == '-') && i > start) {
terms.add(s.substring(start, i));
start = i;
}
}
terms.add(s.substring(start));
for (final term in terms) {
if (term.isEmpty) continue;
// Parse each term
final termPattern = RegExp(r'^([+-]?)(.*?)x(?:\^(\d+))?$|^([+-]?)(.*?)$');
final match = termPattern.firstMatch(term);
if (match != null) {
if (match.group(5) != null) {
// Constant term
final sign = match.group(4) ?? '+';
final value = match.group(5)!;
final coeffStr = sign == '+' && value.isNotEmpty
? value
: '$sign$value';
coeffs[0] = _combineCoefficients(coeffs[0], coeffStr);
} else {
// x term
final sign = match.group(1) ?? '+';
final coeffPart = match.group(2) ?? '';
final power = match.group(3) != null ? int.parse(match.group(3)!) : 1;
String coeffStr;
if (coeffPart.isEmpty) {
coeffStr = sign == '+' ? '1' : '-1';
} else {
coeffStr = sign == '+' ? coeffPart : '$sign$coeffPart';
}
coeffs[power] = _combineCoefficients(coeffs[power], coeffStr);
}
}
}
return coeffs;
}
/// 合并系数,保持符号形式
String _combineCoefficients(String? existing, String newCoeff) {
if (existing == null || existing == '0') return newCoeff;
if (newCoeff == '0') return existing;
// 简化逻辑:如果都是数字,可以相加;否则保持原样
final existingNum = double.tryParse(existing);
final newNum = double.tryParse(newCoeff);
if (existingNum != null && newNum != null) {
final sum = existingNum + newNum;
return sum.toString();
}
// 如果包含符号表达式,直接连接
return '$existing+$newCoeff'.replaceAll('+-', '-');
}
/// 减去系数
String _subtractCoefficients(String a, String b) {
if (a == '0') return b.startsWith('-') ? b.substring(1) : '-$b';
if (b == '0') return a;
final aNum = double.tryParse(a);
final bNum = double.tryParse(b);
if (aNum != null && bNum != null) {
final result = aNum - bNum;
return result.toString();
}
// 符号表达式相减
return '$a-${b.startsWith('-') ? b.substring(1) : b}';
}
/// 计算判别式,保持符号形式
String _calculateDeltaSymbolic(String a, String b, String c) {
// Delta = b^2 - 4ac
// 计算 b^2
String bSquared;
if (b == '0') {
bSquared = '0';
} else if (b == '1') {
bSquared = '1';
} else if (b == '-1') {
bSquared = '1';
} else if (b.startsWith('-')) {
final absB = b.substring(1);
bSquared = '$absB^2';
} else {
bSquared = '$b^2';
}
// 计算 4ac
String fourAC;
if (a == '0' || c == '0') {
fourAC = '0';
} else {
// 处理符号
String aCoeff = a;
String cCoeff = c;
// 如果 a 或 c 是负数,需要处理符号
bool aNegative = a.startsWith('-');
bool cNegative = c.startsWith('-');
if (aNegative) aCoeff = a.substring(1);
if (cNegative) cCoeff = c.substring(1);
String acProduct;
if (aCoeff == '1' && cCoeff == '1') {
acProduct = '1';
} else if (aCoeff == '1') {
acProduct = cCoeff;
} else if (cCoeff == '1') {
acProduct = aCoeff;
} else {
acProduct = '$aCoeff \\cdot $cCoeff';
}
// 确定 4ac 的符号
bool productNegative = aNegative != cNegative;
String fourACValue = '4 \\cdot $acProduct';
if (productNegative) {
fourAC = '-$fourACValue';
} else {
fourAC = fourACValue;
}
}
// 计算 Delta = b^2 - 4ac
if (bSquared == '0' && fourAC == '0') {
return '0';
} else if (bSquared == '0') {
return fourAC.startsWith('-') ? fourAC.substring(1) : '-$fourAC';
} else if (fourAC == '0') {
return bSquared;
} else {
String sign = fourAC.startsWith('-') ? '+' : '-';
String absFourAC = fourAC.startsWith('-') ? fourAC.substring(1) : fourAC;
return '$bSquared $sign $absFourAC';
}
}
Rational _rationalFromDouble(double value, {int maxPrecision = 12}) {
// 限制小数精度,避免无限循环小数
final str = value.toStringAsFixed(maxPrecision);
if (!str.contains('.')) {
return Rational.parse(str);
}
final parts = str.split('.');
final integerPart = parts[0];
final fractionalPart = parts[1];
final numerator = BigInt.parse(integerPart + fractionalPart);
final denominator = BigInt.from(10).pow(fractionalPart.length);
return Rational(numerator, denominator);
}
}

View File

@@ -1,6 +1,22 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
url: "https://pub.dev"
source: hosted
version: "85.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
url: "https://pub.dev"
source: hosted
version: "7.7.1"
ansicolor:
dependency: transitive
description:
@@ -57,6 +73,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.4"
cli_config:
dependency: transitive
description:
name: cli_config
sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
url: "https://pub.dev"
source: hosted
version: "0.2.0"
cli_util:
dependency: transitive
description:
@@ -81,6 +105,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.2"
coverage:
dependency: transitive
description:
name: coverage
sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d"
url: "https://pub.dev"
source: hosted
version: "1.15.0"
crypto:
dependency: transitive
description:
@@ -105,6 +145,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.8"
equatable:
dependency: transitive
description:
name: equatable
sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7"
url: "https://pub.dev"
source: hosted
version: "2.0.7"
fake_async:
dependency: transitive
description:
@@ -121,6 +169,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.4"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fl_chart:
dependency: "direct main"
description:
name: fl_chart
sha256: "00b74ae680df6b1135bdbea00a7d1fc072a9180b7c3f3702e4b19a9943f5ed7d"
url: "https://pub.dev"
source: hosted
version: "0.66.2"
flutter:
dependency: "direct main"
description: flutter
@@ -176,14 +240,30 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob:
dependency: transitive
description:
name: glob
sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
url: "https://pub.dev"
source: hosted
version: "2.1.3"
go_router:
dependency: "direct main"
description:
name: go_router
sha256: f02fd7d2a4dc512fec615529824fdd217fecb3a3d3de68360293a551f21634b3
sha256: eb059dfe59f08546e9787f895bd01652076f996bcbf485a8609ef990419ad227
url: "https://pub.dev"
source: hosted
version: "14.8.1"
version: "16.2.1"
google_fonts:
dependency: "direct main"
description:
@@ -208,6 +288,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.5.0"
http_multi_server:
dependency: transitive
description:
name: http_multi_server
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
url: "https://pub.dev"
source: hosted
version: "3.2.2"
http_parser:
dependency: transitive
description:
@@ -224,6 +312,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.5.4"
io:
dependency: transitive
description:
name: io
sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
json_annotation:
dependency: transitive
description:
@@ -312,6 +416,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.16.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
@@ -320,6 +432,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.0"
node_preamble:
dependency: transitive
description:
name: node_preamble
sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
package_config:
dependency: transitive
description:
name: package_config
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
url: "https://pub.dev"
source: hosted
version: "2.2.0"
path:
dependency: transitive
description:
@@ -408,6 +536,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pool:
dependency: transitive
description:
name: pool
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
url: "https://pub.dev"
source: hosted
version: "1.5.1"
posix:
dependency: transitive
description:
@@ -424,11 +560,75 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
rational:
dependency: "direct main"
description:
name: rational
sha256: cb808fb6f1a839e6fc5f7d8cb3b0a10e1db48b3be102de73938c627f0b636336
url: "https://pub.dev"
source: hosted
version: "2.2.3"
shelf:
dependency: transitive
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
shelf_packages_handler:
dependency: transitive
description:
name: shelf_packages_handler
sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
shelf_static:
dependency: transitive
description:
name: shelf_static
sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
url: "https://pub.dev"
source: hosted
version: "1.1.3"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_map_stack_trace:
dependency: transitive
description:
name: source_map_stack_trace
sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
url: "https://pub.dev"
source: hosted
version: "2.1.2"
source_maps:
dependency: transitive
description:
name: source_maps
sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812"
url: "https://pub.dev"
source: hosted
version: "0.10.13"
source_span:
dependency: transitive
description:
@@ -469,6 +669,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test:
dependency: "direct dev"
description:
name: test
sha256: "65e29d831719be0591f7b3b1a32a3cda258ec98c58c7b25f7b84241bc31215bb"
url: "https://pub.dev"
source: hosted
version: "1.26.2"
test_api:
dependency: transitive
description:
@@ -477,6 +685,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.6"
test_core:
dependency: transitive
description:
name: test_core
sha256: "80bf5a02b60af04b09e14f6fe68b921aad119493e26e490deaca5993fef1b05a"
url: "https://pub.dev"
source: hosted
version: "0.6.11"
tuple:
dependency: transitive
description:
@@ -605,6 +821,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "15.0.2"
watcher:
dependency: transitive
description:
name: watcher
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
url: "https://pub.dev"
source: hosted
version: "1.1.3"
web:
dependency: transitive
description:
@@ -613,6 +837,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web_socket:
dependency: transitive
description:
name: web_socket
sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
web_socket_channel:
dependency: transitive
description:
name: web_socket_channel
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webkit_inspection_protocol:
dependency: transitive
description:
name: webkit_inspection_protocol
sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
xdg_directories:
dependency: transitive
description:

View File

@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+3
version: 1.0.0+4
environment:
sdk: ^3.9.2
@@ -37,8 +37,10 @@ dependencies:
math_expressions: ^3.1.0
latext: ^0.5.1
google_fonts: ^6.3.1
go_router: ^14.2.0
url_launcher: ^6.3.0
go_router: ^16.2.1
url_launcher: ^6.3.2
rational: ^2.2.3
fl_chart: ^0.66.1
dev_dependencies:
flutter_test:
@@ -52,6 +54,7 @@ dev_dependencies:
flutter_lints: ^6.0.0
flutter_native_splash: ^2.4.6
flutter_launcher_icons: ^0.14.4
test: ^1.26.2
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

104
test/calculator_test.dart Normal file
View File

@@ -0,0 +1,104 @@
import 'package:simple_math_calc/parser.dart';
import 'package:test/test.dart';
void main() {
group('整数', () {
test('加法', () {
var expr = Parser("2 + 3").parse();
expect(expr.evaluate().toString(), "5");
});
test('乘法', () {
var expr = Parser("4 * 5").parse();
expect(expr.evaluate().toString(), "20");
});
});
group('分数', () {
test('简单分数', () {
var expr = Parser("1/2").parse();
expect(expr.evaluate().toString(), "1/2");
});
test('分数加法', () {
var expr = Parser("1/2 + 3/4").parse();
expect(expr.evaluate().toString().replaceAll(' ', ''), "5/4");
});
test('分数与整数相乘', () {
var expr = Parser("2 * 3/4").parse();
expect(expr.evaluate().toString(), "3/2");
});
});
group('开平方', () {
test('完全平方数', () {
var expr = Parser("sqrt(9)").parse();
expect(expr.evaluate().toString(), "3");
});
test('非完全平方数', () {
var expr = Parser("sqrt(8)").parse();
expect(expr.simplify().toString().replaceAll(' ', ''), "(2*sqrt(2))");
});
});
group('组合表达式', () {
test('sqrt + 整数', () {
var expr = Parser("2 + sqrt(9)").parse();
expect(expr.simplify().toString().replaceAll(' ', ''), "(2+3)");
});
test('分数 + sqrt', () {
var expr = Parser("sqrt(8)/4 + 1/2").parse();
expect(
expr.evaluate().toString().replaceAll(' ', ''),
"((sqrt(2)/2)+1/2)",
);
});
});
group('加减除优先级', () {
test('减法', () {
var expr = Parser("5 - 2").parse();
expect(expr.evaluate().toString(), "3");
});
test('除法', () {
var expr = Parser("6 / 3").parse();
expect(expr.evaluate().toString(), "2");
});
test('加法和乘法优先级', () {
var expr = Parser("1 + 2 * 3").parse();
expect(expr.evaluate().toString(), "7");
});
test('加减混合', () {
var expr = Parser("10 - 3 + 2").parse();
expect(expr.evaluate().toString(), "9");
});
test('括号优先级', () {
var expr = Parser("(1 + 2) * 3").parse();
expect(expr.evaluate().toString(), "9");
});
});
group('三角函数', () {
test('cos(0)', () {
var expr = Parser("cos(0)").parse();
expect(expr.evaluate().toString(), "1.0");
});
test('sin(0)', () {
var expr = Parser("sin(0)").parse();
expect(expr.evaluate().toString(), "0.0");
});
test('tan(0)', () {
var expr = Parser("tan(0)").parse();
expect(expr.evaluate().toString(), "0.0");
});
});
}

62
test/core_test.dart Normal file
View File

@@ -0,0 +1,62 @@
import 'package:test/test.dart';
import 'package:simple_math_calc/calculator.dart';
import 'package:simple_math_calc/parser.dart';
void main() {
group('解析器测试', () {
test('简单加法', () {
final parser = Parser('2 + 3');
final expr = parser.parse();
final result = expr.evaluate();
expect(result.toString(), '5');
});
test('乘法和加法优先级', () {
final parser = Parser('2 + 3 * 4');
final expr = parser.parse();
final result = expr.evaluate();
expect(result.toString(), '14');
});
test('括号优先级', () {
final parser = Parser('(2 + 3) * 4');
final expr = parser.parse();
final result = expr.evaluate();
expect(result.toString(), '20');
});
test('除法', () {
final parser = Parser('10 / 2');
final expr = parser.parse();
final result = expr.evaluate();
expect(result.toString(), '5');
});
test('平方根', () {
final parser = Parser('sqrt(9)');
final expr = parser.parse();
final result = expr.evaluate();
expect(result.toString(), '3');
});
});
group('计算器测试', () {
test('分数简化', () {
final fraction = FractionExpr(4, 8);
final simplified = fraction.simplify();
expect(simplified.toString(), '1/2');
});
test('分数加法', () {
final expr = AddExpr(FractionExpr(1, 2), FractionExpr(1, 4));
final result = expr.evaluate();
expect(result.toString(), '3/4');
});
test('分数乘法', () {
final expr = MulExpr(FractionExpr(1, 2), FractionExpr(2, 3));
final result = expr.evaluate();
expect(result.toString(), '1/3');
});
});
}

109
test/solver_test.dart Normal file
View File

@@ -0,0 +1,109 @@
import 'package:flutter/widgets.dart';
import 'package:test/test.dart';
import 'package:simple_math_calc/solver.dart';
void main() {
group('求解器测试', () {
final solver = SolverService();
test('简单表达式求值', () {
final result = solver.solve('2 + 3 * 4');
expect(result.finalAnswer, contains('14'));
});
test('简单方程求解', () {
final result = solver.solve('2x + 3 = 7');
expect(result.finalAnswer, contains('x = 2'));
});
test('二次方程求解', () {
final result = solver.solve('x^2 - 5x + 6 = 0');
debugPrint(result.finalAnswer);
expect(
result.finalAnswer.contains('x_1 = 2') &&
result.finalAnswer.contains('x_2 = 3'),
true,
);
});
test('三角函数求值', () {
final result = solver.solve('sin(30)');
debugPrint(result.finalAnswer);
expect(result.finalAnswer.contains(r'\frac{1}{2}'), true);
});
test('带括号的复杂表达式', () {
final result = solver.solve('(2 + 3) * 4');
expect(result.finalAnswer, contains('20'));
});
test('括号展开的二次方程', () {
final result = solver.solve('(x+8)(x+1)=-12');
debugPrint('Result for (x+8)(x+1)=-12: ${result.finalAnswer}');
// 这个方程应该被识别为一元二次方程,正确解应该是 x = -4 或 x = -5
expect(
result.steps.any((step) => step.title == '整理方程'),
true,
reason: '方程应被识别为一元二次方程并进行整理',
);
expect(
(result.finalAnswer.contains('-4') &&
result.finalAnswer.contains('-5')) ||
result.finalAnswer.contains('x = -4') ||
result.finalAnswer.contains('x = -5'),
true,
);
});
test('二次方程根的简化', () {
final result = solver.solve('x^2 - 4x - 5 = 0');
debugPrint('Result for x^2 - 4x - 5 = 0: ${result.finalAnswer}');
// 这个方程的根应该是 x = (4 ± √(16 + 20))/2 = (4 ± √36)/2 = (4 ± 6)/2
// 所以 x1 = (4 + 6)/2 = 5, x2 = (4 - 6)/2 = -1
expect(
(result.finalAnswer.contains('x_1 = 5') &&
result.finalAnswer.contains('x_2 = -1')) ||
(result.finalAnswer.contains('x_1 = -1') &&
result.finalAnswer.contains('x_2 = 5')),
true,
reason: '方程 x^2 - 4x - 5 = 0 的根应该被正确简化',
);
});
test('二次方程精确度改进', () {
final result = solver.solve('x^2 - 2x - 1 = 0');
debugPrint('Result for x^2 - 2x - 1 = 0: ${result.finalAnswer}');
// 这个方程的根应该是 x = (2 ± √(4 + 4))/2 = (2 ± √8)/2 = (2 ± 2√2)/2 = 1 ± √2
// 验证结果包含正确的根格式
expect(
result.finalAnswer.contains('x_1') &&
result.finalAnswer.contains('x_2'),
true,
reason: '方程应该有两个根',
);
expect(
result.finalAnswer.contains('1 +') ||
result.finalAnswer.contains('1 -'),
true,
reason: '根应该以 1 ± √2 的形式出现',
);
});
test('无实数解的二次方程', () {
final result = solver.solve('x(55-3x+2)=300');
debugPrint('Result for x(55-3x+2)=300: ${result.finalAnswer}');
// 这个方程展开后为 -3x² + 57x - 300 = 0判别式为负数应该无实数解
expect(
result.steps.any((step) => step.formula.contains('无实数解')),
true,
reason: '方程应该被识别为无实数解',
);
expect(
result.finalAnswer.contains('x_1') &&
result.finalAnswer.contains('x_2'),
true,
reason: '应该提供复数根',
);
});
});
}

21
test_expand.dart Normal file
View File

@@ -0,0 +1,21 @@
import 'lib/solver.dart';
void main() {
final solver = SolverService();
// Test the problematic case
final input = '(x+8)(x+1)=-12';
print('Input: $input');
try {
final result = solver.solve(input);
print('Result: ${result.finalAnswer}');
print('Steps:');
for (final step in result.steps) {
print('Step ${step.stepNumber}: ${step.title}');
print(' Formula: ${step.formula}');
}
} catch (e) {
print('Error: $e');
}
}