Compare commits
3 Commits
5cf66cd1f2
...
a1d4400455
Author | SHA1 | Date | |
---|---|---|---|
a1d4400455
|
|||
d652df407f
|
|||
d26c29613b
|
@@ -43,22 +43,26 @@ class Parser {
|
||||
Expr parseMul() {
|
||||
var expr = parsePow();
|
||||
skipSpaces();
|
||||
while (!isEnd && (current == '*' || current == '/')) {
|
||||
while (!isEnd &&
|
||||
(current == '*' ||
|
||||
current == '/' ||
|
||||
current == '%' ||
|
||||
RegExp(r'[a-zA-Z\d]').hasMatch(current) ||
|
||||
current == '(')) {
|
||||
if (current == '*' || current == '/') {
|
||||
var op = current;
|
||||
eat();
|
||||
var right = parsePow();
|
||||
if (op == '*') {
|
||||
expr = MulExpr(expr, right);
|
||||
} else {
|
||||
expr = DivExpr(expr, right);
|
||||
}
|
||||
skipSpaces();
|
||||
}
|
||||
// Handle percentage operator
|
||||
skipSpaces();
|
||||
if (!isEnd && current == '%') {
|
||||
expr = op == '*' ? MulExpr(expr, right) : DivExpr(expr, right);
|
||||
} else if (current == '%') {
|
||||
eat();
|
||||
expr = PercentExpr(expr);
|
||||
} else {
|
||||
// implicit multiplication
|
||||
var right = parsePow();
|
||||
expr = MulExpr(expr, right);
|
||||
}
|
||||
skipSpaces();
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
@@ -47,6 +47,22 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
||||
|
||||
final input = _controller.text.trim();
|
||||
final normalizedInput = input.replaceAll(' ', '');
|
||||
|
||||
// 如果当前已经是函数模式,保持函数模式
|
||||
if (_isFunctionMode) {
|
||||
// 重新检查表达式是否仍然可绘制(以防用户修改了表达式)
|
||||
if (_solverService.isGraphableExpression(normalizedInput)) {
|
||||
// 保持在函数模式,不做任何改变
|
||||
return;
|
||||
} else {
|
||||
// 表达式不再可绘制,切换回普通模式
|
||||
setState(() {
|
||||
_isFunctionMode = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否为函数表达式(优先使用简单y=检测)
|
||||
if (normalizedInput.toLowerCase().startsWith('y=')) {
|
||||
setState(() {
|
||||
_isFunctionMode = true;
|
||||
@@ -55,6 +71,16 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
||||
return;
|
||||
}
|
||||
|
||||
// 备用检查:使用solver进行更复杂的表达式检测
|
||||
if (_solverService.isGraphableExpression(normalizedInput)) {
|
||||
setState(() {
|
||||
_isFunctionMode = true;
|
||||
_result = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 普通表达式求解
|
||||
setState(() {
|
||||
_isFunctionMode = false;
|
||||
_isLoading = true;
|
||||
|
104
lib/solver.dart
104
lib/solver.dart
@@ -1,9 +1,9 @@
|
||||
import 'dart:math';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'dart:developer' show log;
|
||||
import 'dart:math' hide log;
|
||||
import 'package:rational/rational.dart';
|
||||
import 'package:simple_math_calc/calculator.dart';
|
||||
import 'package:simple_math_calc/parser.dart';
|
||||
import 'models/calculation_step.dart';
|
||||
import 'calculator.dart';
|
||||
import 'parser.dart';
|
||||
|
||||
/// 帮助解析一元一次方程 ax+b=cx+d 的辅助类
|
||||
class LinearEquationParts {
|
||||
@@ -512,6 +512,92 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查表达式是否可绘制(包含变量x且可以被求值)
|
||||
bool isGraphableExpression(String expression) {
|
||||
try {
|
||||
// 移除空格并转换为小写
|
||||
String cleanExpr = expression.replaceAll(' ', '').toLowerCase();
|
||||
|
||||
// 如果以 y= 开头,去掉前缀
|
||||
if (cleanExpr.startsWith('y=')) {
|
||||
cleanExpr = cleanExpr.substring(2);
|
||||
}
|
||||
|
||||
// 不能包含等号(方程而不是函数表达式)
|
||||
if (cleanExpr.contains('=')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 必须包含变量x
|
||||
if (!cleanExpr.contains('x')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 尝试展开表达式(如果包含括号)
|
||||
String processedExpr = cleanExpr;
|
||||
if (processedExpr.contains('(')) {
|
||||
processedExpr = _expandExpressions(processedExpr);
|
||||
}
|
||||
|
||||
// 尝试解析表达式
|
||||
final parser = Parser(processedExpr);
|
||||
final expr = parser.parse();
|
||||
|
||||
// 测试在几个点上是否可以求值
|
||||
final testPoints = [-1.0, 0.0, 1.0];
|
||||
for (final x in testPoints) {
|
||||
try {
|
||||
final substituted = expr.substitute('x', DoubleExpr(x));
|
||||
final evaluated = substituted.evaluate();
|
||||
if (evaluated is DoubleExpr &&
|
||||
evaluated.value.isFinite &&
|
||||
!evaluated.value.isNaN) {
|
||||
// 至少有一个点可以求值就算成功
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
// 继续测试其他点
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 准备函数表达式用于绘图(展开因式形式)
|
||||
String prepareFunctionForGraphing(String expression) {
|
||||
// 移除空格并转换为小写
|
||||
String cleanExpr = expression.replaceAll(' ', '').toLowerCase();
|
||||
|
||||
// 如果以 y= 开头,去掉前缀
|
||||
if (cleanExpr.startsWith('y=')) {
|
||||
cleanExpr = cleanExpr.substring(2);
|
||||
}
|
||||
|
||||
// 如果表达式包含括号,进行展开
|
||||
if (cleanExpr.contains('(')) {
|
||||
cleanExpr = _expandExpressions(cleanExpr);
|
||||
}
|
||||
|
||||
// 清理格式:移除不必要的.0后缀和简化格式
|
||||
cleanExpr = cleanExpr
|
||||
.replaceAll('.0', '') // 移除所有.0
|
||||
.replaceAll('+0', '') // 移除+0
|
||||
.replaceAll('-0', '') // 移除-0
|
||||
.replaceAll('1x^2', 'x^2') // 1x^2 -> x^2
|
||||
.replaceAll('1x', 'x'); // 1x -> x
|
||||
|
||||
// 移除开头的+号
|
||||
if (cleanExpr.startsWith('+')) {
|
||||
cleanExpr = cleanExpr.substring(1);
|
||||
}
|
||||
|
||||
return cleanExpr;
|
||||
}
|
||||
|
||||
/// ---- 辅助函数 ----
|
||||
|
||||
String _expandExpressions(String input) {
|
||||
@@ -554,26 +640,26 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
||||
if (factorMulMatch != null) {
|
||||
final factor1 = factorMulMatch.group(1)!;
|
||||
final factor2 = factorMulMatch.group(2)!;
|
||||
debugPrint('Expanding: ($factor1) * ($factor2)');
|
||||
log('Expanding: ($factor1) * ($factor2)');
|
||||
|
||||
final coeffs1 = _parsePolynomial(factor1);
|
||||
final coeffs2 = _parsePolynomial(factor2);
|
||||
debugPrint('Coeffs1: $coeffs1, Coeffs2: $coeffs2');
|
||||
log('Coeffs1: $coeffs1, Coeffs2: $coeffs2');
|
||||
|
||||
final a = coeffs1[1] ?? 0;
|
||||
final b = coeffs1[0] ?? 0;
|
||||
final c = coeffs2[1] ?? 0;
|
||||
final d = coeffs2[0] ?? 0;
|
||||
debugPrint('a=$a, b=$b, c=$c, d=$d');
|
||||
log('a=$a, b=$b, c=$c, d=$d');
|
||||
|
||||
final newA = a * c;
|
||||
final newB = a * d + b * c;
|
||||
final newC = b * d;
|
||||
debugPrint('newA=$newA, newB=$newB, newC=$newC');
|
||||
log('newA=$newA, newB=$newB, newC=$newC');
|
||||
|
||||
final expanded =
|
||||
'${newA}x^2${newB >= 0 ? '+' : ''}${newB}x${newC >= 0 ? '+' : ''}$newC';
|
||||
debugPrint('Expanded result: $expanded');
|
||||
log('Expanded result: $expanded');
|
||||
|
||||
result = result.replaceFirst(factorMulMatch.group(0)!, expanded);
|
||||
iterationCount++;
|
||||
|
@@ -1,7 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:latext/latext.dart';
|
||||
import 'package:simple_math_calc/parser.dart';
|
||||
import 'package:simple_math_calc/calculator.dart';
|
||||
import 'package:simple_math_calc/solver.dart';
|
||||
import 'dart:math';
|
||||
|
||||
class GraphCard extends StatefulWidget {
|
||||
@@ -23,15 +26,16 @@ class GraphCard extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _GraphCardState extends State<GraphCard> {
|
||||
final SolverService _solverService = SolverService();
|
||||
FlSpot? _currentTouchedPoint;
|
||||
|
||||
/// 生成函数图表的点
|
||||
List<FlSpot> _generatePlotPoints(String expression, double zoomFactor) {
|
||||
try {
|
||||
// 只处理 y=... 格式的函数
|
||||
String normalized = expression.replaceAll(' ', '');
|
||||
if (!normalized.toLowerCase().startsWith('y=')) {
|
||||
return [];
|
||||
}
|
||||
String functionExpr = normalized.substring(2);
|
||||
// 使用solver准备函数表达式(展开因式形式)
|
||||
String functionExpr = _solverService.prepareFunctionForGraphing(
|
||||
expression,
|
||||
);
|
||||
|
||||
// 如果表达式不包含 x,返回空列表
|
||||
if (!functionExpr.contains('x') && !functionExpr.contains('X')) {
|
||||
@@ -53,6 +57,12 @@ class _GraphCardState extends State<GraphCard> {
|
||||
(match) => '${match.group(1)}*${match.group(2)}',
|
||||
);
|
||||
|
||||
// 在 % 和变量或数字之间插入乘号 (如 80%x -> 80%*x)
|
||||
functionExpr = functionExpr.replaceAllMapped(
|
||||
RegExp(r'%([a-zA-Z\d])'),
|
||||
(match) => '%*${match.group(1)}',
|
||||
);
|
||||
|
||||
// 解析表达式
|
||||
final parser = Parser(functionExpr);
|
||||
final expr = parser.parse();
|
||||
@@ -138,6 +148,19 @@ class _GraphCardState extends State<GraphCard> {
|
||||
);
|
||||
}
|
||||
|
||||
String _formatAxisValue(double value) {
|
||||
if (value.abs() < 1e-10) return "0";
|
||||
if ((value - value.roundToDouble()).abs() < 1e-10) {
|
||||
return value.round().toString();
|
||||
}
|
||||
double absVal = value.abs();
|
||||
if (absVal >= 100) return value.toStringAsFixed(0);
|
||||
if (absVal >= 10) return value.toStringAsFixed(1);
|
||||
if (absVal >= 1) return value.toStringAsFixed(2);
|
||||
if (absVal >= 0.1) return value.toStringAsFixed(3);
|
||||
return value.toStringAsFixed(4);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
@@ -205,22 +228,52 @@ class _GraphCardState extends State<GraphCard> {
|
||||
leftTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 80,
|
||||
reservedSize: 60,
|
||||
interval: (bounds.maxY - bounds.minY) / 8,
|
||||
getTitlesWidget: (value, meta) =>
|
||||
SideTitleWidget(
|
||||
axisSide: meta.axisSide,
|
||||
child: Text(value.toStringAsFixed(2)),
|
||||
child: Text(
|
||||
_formatAxisValue(value),
|
||||
style: GoogleFonts.robotoFlex(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
bottomTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 24,
|
||||
getTitlesWidget: (value, meta) =>
|
||||
SideTitleWidget(
|
||||
reservedSize: 80,
|
||||
interval: (bounds.maxX - bounds.minX) / 10,
|
||||
getTitlesWidget: (value, meta) => SideTitleWidget(
|
||||
axisSide: meta.axisSide,
|
||||
child: Text(value.toStringAsFixed(2)),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: _formatAxisValue(value)
|
||||
.split('')
|
||||
.map(
|
||||
(char) => ['-', '.'].contains(char)
|
||||
? Transform.rotate(
|
||||
angle: pi / 2,
|
||||
child: Text(
|
||||
char,
|
||||
style:
|
||||
GoogleFonts.robotoFlex(
|
||||
height: char == '.'
|
||||
? 0.7
|
||||
: 0.9,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
char,
|
||||
style: GoogleFonts.robotoFlex(
|
||||
height: 0.9,
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -239,6 +292,17 @@ class _GraphCardState extends State<GraphCard> {
|
||||
),
|
||||
lineTouchData: LineTouchData(
|
||||
enabled: true,
|
||||
touchCallback: (event, response) {
|
||||
if (response != null &&
|
||||
response.lineBarSpots != null &&
|
||||
response.lineBarSpots!.isNotEmpty) {
|
||||
setState(() {
|
||||
_currentTouchedPoint =
|
||||
response.lineBarSpots!.first;
|
||||
});
|
||||
}
|
||||
// Keep the last touched point visible
|
||||
},
|
||||
touchTooltipData: LineTouchTooltipData(
|
||||
getTooltipItems: (touchedSpots) {
|
||||
return touchedSpots.map((spot) {
|
||||
@@ -269,6 +333,28 @@ class _GraphCardState extends State<GraphCard> {
|
||||
},
|
||||
),
|
||||
),
|
||||
if (_currentTouchedPoint != null)
|
||||
Container(
|
||||
margin: const EdgeInsets.only(top: 16),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
LaTexT(
|
||||
laTeXCode: Text(
|
||||
'\$\$x = ${_currentTouchedPoint!.x.toStringAsFixed(4)},\\quad y = ${_currentTouchedPoint!.y.toStringAsFixed(4)}\$\$',
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
@@ -105,5 +105,35 @@ void main() {
|
||||
reason: '应该提供复数根',
|
||||
);
|
||||
});
|
||||
|
||||
test('可绘制函数表达式检测', () {
|
||||
// 测试可绘制的函数表达式
|
||||
expect(solver.isGraphableExpression('y=x^2'), true);
|
||||
expect(solver.isGraphableExpression('x^2+2x+1'), true);
|
||||
expect(solver.isGraphableExpression('(x-1)(x+3)'), true);
|
||||
|
||||
// 测试不可绘制的表达式
|
||||
expect(solver.isGraphableExpression('2+3'), false);
|
||||
expect(solver.isGraphableExpression('hello'), false);
|
||||
expect(solver.isGraphableExpression('x^2=4'), false); // 方程而不是函数
|
||||
});
|
||||
|
||||
test('函数表达式预处理', () {
|
||||
// 测试因式展开
|
||||
final expanded = solver.prepareFunctionForGraphing('y=(x-1)(x+3)');
|
||||
expect(expanded, 'x^2+2x-3');
|
||||
|
||||
// 测试已展开的表达式
|
||||
final alreadyExpanded = solver.prepareFunctionForGraphing('x^2+2x+1');
|
||||
expect(alreadyExpanded, 'x^2+2x+1');
|
||||
|
||||
// 测试无y=前缀的表达式
|
||||
final noPrefix = solver.prepareFunctionForGraphing('(x-1)(x+3)');
|
||||
expect(noPrefix, 'x^2+2x-3');
|
||||
|
||||
// 测试百分比表达式
|
||||
final percentExpr = solver.prepareFunctionForGraphing('y=80%x');
|
||||
expect(percentExpr, '80%x');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
Reference in New Issue
Block a user