Compare commits
8 Commits
3f0bcb472d
...
1.0.0+4
Author | SHA1 | Date | |
---|---|---|---|
722ef9ca21
|
|||
37e3e4ecd3
|
|||
bd97721dbc
|
|||
a02325052c
|
|||
4c11866da0
|
|||
18b4406ece
|
|||
bf74f8d176
|
|||
35ea42ce9b
|
@@ -1,6 +1,6 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<application
|
<application
|
||||||
android:label="simple_math_calc"
|
android:label="SimpleMathCalc"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/launcher_icon">
|
android:icon="@mipmap/launcher_icon">
|
||||||
<activity
|
<activity
|
||||||
|
@@ -1,9 +1,9 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:google_fonts/google_fonts.dart';
|
|
||||||
import 'package:latext/latext.dart';
|
import 'package:latext/latext.dart';
|
||||||
import 'package:simple_math_calc/models/calculation_step.dart';
|
import 'package:simple_math_calc/models/calculation_step.dart';
|
||||||
import 'package:simple_math_calc/solver.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';
|
import 'dart:math';
|
||||||
|
|
||||||
class CalculatorHomePage extends StatefulWidget {
|
class CalculatorHomePage extends StatefulWidget {
|
||||||
@@ -20,25 +20,141 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
|||||||
|
|
||||||
CalculationResult? _result;
|
CalculationResult? _result;
|
||||||
bool _isLoading = false;
|
bool _isLoading = false;
|
||||||
bool _isInputFocused = false;
|
double _zoomFactor = 1.0;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_focusNode = FocusNode();
|
_focusNode = FocusNode();
|
||||||
_focusNode.addListener(() {
|
_controller.addListener(_onTextChanged);
|
||||||
setState(() {
|
|
||||||
_isInputFocused = _focusNode.hasFocus;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
_controller.removeListener(_onTextChanged);
|
||||||
_focusNode.dispose();
|
_focusNode.dispose();
|
||||||
super.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() {
|
void _solveEquation() {
|
||||||
if (_controller.text.isEmpty) {
|
if (_controller.text.isEmpty) {
|
||||||
return;
|
return;
|
||||||
@@ -69,21 +185,23 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _insertSymbol(String symbol) {
|
void _zoomIn() {
|
||||||
final text = _controller.text;
|
setState(() {
|
||||||
final selection = _controller.selection;
|
_zoomFactor = (_zoomFactor * 0.8).clamp(0.1, 10.0);
|
||||||
final newText = text.replaceRange(selection.start, selection.end, symbol);
|
});
|
||||||
_controller.text = newText;
|
}
|
||||||
_controller.selection = TextSelection.collapsed(
|
|
||||||
offset: selection.start + symbol.length,
|
void _zoomOut() {
|
||||||
);
|
setState(() {
|
||||||
|
_zoomFactor = (_zoomFactor * 1.25).clamp(0.1, 10.0);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('方程与表达式计算器'),
|
title: const Text('计算器'),
|
||||||
centerTitle: false,
|
centerTitle: false,
|
||||||
leading: const Icon(Icons.calculate_outlined),
|
leading: const Icon(Icons.calculate_outlined),
|
||||||
),
|
),
|
||||||
@@ -105,12 +223,10 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
|||||||
floatingLabelAlignment: FloatingLabelAlignment.center,
|
floatingLabelAlignment: FloatingLabelAlignment.center,
|
||||||
hintText: '例如: 2x^2 - 8x + 6 = 0',
|
hintText: '例如: 2x^2 - 8x + 6 = 0',
|
||||||
),
|
),
|
||||||
keyboardType: kIsWeb
|
keyboardType: TextInputType.numberWithOptions(
|
||||||
? TextInputType.numberWithOptions(
|
|
||||||
signed: true,
|
signed: true,
|
||||||
decimal: true,
|
decimal: true,
|
||||||
)
|
),
|
||||||
: TextInputType.number,
|
|
||||||
onSubmitted: (_) => _solveEquation(),
|
onSubmitted: (_) => _solveEquation(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -128,7 +244,6 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
|||||||
? const Center(child: Text('请输入方程开始计算'))
|
? const Center(child: Text('请输入方程开始计算'))
|
||||||
: buildResultView(_result!),
|
: buildResultView(_result!),
|
||||||
),
|
),
|
||||||
if (_isInputFocused) _buildToolbar(),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -239,155 +354,107 @@ class _CalculatorHomePageState extends State<CalculatorHomePage> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
const SizedBox(height: 16),
|
||||||
);
|
Card(
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildToolbar() {
|
|
||||||
return Material(
|
|
||||||
elevation: 8,
|
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8),
|
padding: const EdgeInsets.all(16.0),
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
children: [
|
||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
spacing: 8,
|
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Padding(
|
||||||
child: Tooltip(
|
padding: const EdgeInsets.only(left: 4),
|
||||||
message: '左括号',
|
child: Text(
|
||||||
child: FilledButton.tonal(
|
'函数图像',
|
||||||
onPressed: () => _insertSymbol('('),
|
style: Theme.of(context).textTheme.titleMedium,
|
||||||
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('^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(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
spacing: 8,
|
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
IconButton(
|
||||||
child: Tooltip(
|
onPressed: _zoomIn,
|
||||||
message: '加法',
|
icon: Icon(Icons.zoom_in),
|
||||||
child: FilledButton.tonal(
|
tooltip: '放大',
|
||||||
onPressed: () => _insertSymbol('+'),
|
padding: EdgeInsets.zero,
|
||||||
child: Text('+', style: GoogleFonts.robotoMono()),
|
visualDensity: VisualDensity.compact,
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
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: _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,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
214
lib/solver.dart
214
lib/solver.dart
@@ -277,10 +277,9 @@ class SolverService {
|
|||||||
|
|
||||||
final deltaDouble = delta.toDouble();
|
final deltaDouble = delta.toDouble();
|
||||||
if (deltaDouble > 0) {
|
if (deltaDouble > 0) {
|
||||||
// Keep sqrt symbolic instead of evaluating to decimal
|
// Pass delta directly to maintain precision
|
||||||
final sqrtDeltaStr = _formatSqrtExpression(delta.toDouble());
|
final x1Expr = _formatQuadraticRoot(-b, delta, 2 * a, true);
|
||||||
final x1Expr = _formatQuadraticRoot(-b, sqrtDeltaStr, 2 * a, true);
|
final x2Expr = _formatQuadraticRoot(-b, delta, 2 * a, false);
|
||||||
final x2Expr = _formatQuadraticRoot(-b, sqrtDeltaStr, 2 * a, false);
|
|
||||||
|
|
||||||
steps.add(
|
steps.add(
|
||||||
CalculationStep(
|
CalculationStep(
|
||||||
@@ -319,8 +318,9 @@ class SolverService {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Keep sqrt symbolic for complex roots
|
// For complex roots, we need to handle -delta
|
||||||
final sqrtNegDeltaStr = _formatSqrtExpression(-delta.toDouble());
|
final negDelta = -delta;
|
||||||
|
final sqrtNegDeltaStr = _formatSqrtFromRational(negDelta);
|
||||||
final realPart = -b / (2 * a);
|
final realPart = -b / (2 * a);
|
||||||
final imagPartExpr = _formatImaginaryPart(sqrtNegDeltaStr, 2 * a);
|
final imagPartExpr = _formatImaginaryPart(sqrtNegDeltaStr, 2 * a);
|
||||||
|
|
||||||
@@ -1079,76 +1079,166 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
|||||||
|
|
||||||
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
|
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
|
||||||
|
|
||||||
/// 格式化平方根表达式,保持符号形式
|
/// 格式化 Rational 值的平方根表达式,保持符号形式
|
||||||
String _formatSqrtExpression(double value) {
|
String _formatSqrtFromRational(Rational value) {
|
||||||
if (value == 0) return '0';
|
if (value == Rational.zero) return '0';
|
||||||
|
|
||||||
// 处理负数(用于复数根)
|
// 处理负数(用于复数根)
|
||||||
if (value < 0) {
|
if (value < Rational.zero) {
|
||||||
return '\\sqrt{${(-value).toInt()}}';
|
return '\\sqrt{${(-value).toBigInt()}}';
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否为完全平方数
|
// 尝试将 Rational 转换为完全平方数的形式
|
||||||
final sqrtValue = sqrt(value);
|
// 例如: 4/9 -> 2/3, 9/4 -> 3/2, 25/16 -> 5/4 等
|
||||||
final rounded = sqrtValue.round();
|
|
||||||
if ((sqrtValue - rounded).abs() < 1e-10) {
|
|
||||||
return rounded.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 寻找最大的完全平方数因子
|
// 首先简化分数
|
||||||
int maxSquareFactor = 1;
|
final simplified = value;
|
||||||
int intValue = value.toInt();
|
|
||||||
for (int i = 2; i * i <= intValue; i++) {
|
|
||||||
if (intValue % (i * i) == 0) {
|
|
||||||
maxSquareFactor = i * i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final coefficient = sqrt(maxSquareFactor).round();
|
// 检查分子和分母是否都是完全平方数
|
||||||
final remaining = intValue ~/ maxSquareFactor;
|
final numerator = simplified.numerator;
|
||||||
|
final denominator = simplified.denominator;
|
||||||
|
|
||||||
if (remaining == 1) {
|
// 寻找分子和分母的平方根因子
|
||||||
return coefficient == 1
|
BigInt sqrtNumerator = _findSquareRootFactor(numerator);
|
||||||
? '\\sqrt{$intValue}'
|
BigInt sqrtDenominator = _findSquareRootFactor(denominator);
|
||||||
: '$coefficient\\sqrt{$remaining}';
|
|
||||||
} else if (coefficient == 1) {
|
// 计算剩余的分子和分母
|
||||||
return '\\sqrt{$remaining}';
|
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 {
|
} else {
|
||||||
return '$coefficient\\sqrt{$remaining}';
|
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)
|
/// 格式化二次方程的根:(-b ± sqrt(delta)) / (2a)
|
||||||
String _formatQuadraticRoot(
|
String _formatQuadraticRoot(
|
||||||
double b,
|
double b,
|
||||||
String sqrtExpr,
|
Rational delta,
|
||||||
double denominator,
|
double denominator,
|
||||||
bool isPlus,
|
bool isPlus,
|
||||||
) {
|
) {
|
||||||
final sign = isPlus ? '+' : '-';
|
final denomInt = denominator.toInt();
|
||||||
final bStr = b == 0
|
|
||||||
? ''
|
|
||||||
: b > 0
|
|
||||||
? '${b.toInt()}'
|
|
||||||
: '(${b.toInt()})';
|
|
||||||
final denomStr = denominator == 2 ? '2' : denominator.toString();
|
final denomStr = denominator == 2 ? '2' : denominator.toString();
|
||||||
|
|
||||||
|
// Format sqrt(delta) symbolically using the Rational value
|
||||||
|
final sqrtExpr = _formatSqrtFromRational(delta);
|
||||||
|
|
||||||
if (b == 0) {
|
if (b == 0) {
|
||||||
// 简化为 ±sqrt(delta)/denominator
|
// 简化为 ±sqrt(delta)/denominator
|
||||||
if (denominator == 2) {
|
if (denominator == 2) {
|
||||||
return isPlus
|
return isPlus ? '\\frac{$sqrtExpr}{2}' : '-\\frac{$sqrtExpr}{2}';
|
||||||
? '\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{2}'
|
|
||||||
: '-\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{2}';
|
|
||||||
} else {
|
} else {
|
||||||
return isPlus
|
return isPlus
|
||||||
? '\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{$denomStr}'
|
? '\\frac{$sqrtExpr}{$denomStr}'
|
||||||
: '-\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{$denomStr}';
|
: '-\\frac{$sqrtExpr}{$denomStr}';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 完整的表达式:(-b ± sqrt(delta))/denominator
|
// 完整的表达式:(-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
|
final numerator = b > 0
|
||||||
? '-$bStr $sign \\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}'
|
? '-$bStr $signStr $sqrtExpr'
|
||||||
: '(${b.toInt()}) $sign \\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}';
|
: '(${bInt}) $signStr $sqrtExpr';
|
||||||
|
|
||||||
if (denominator == 2) {
|
if (denominator == 2) {
|
||||||
return '\\frac{$numerator}{2}';
|
return '\\frac{$numerator}{2}';
|
||||||
@@ -1157,6 +1247,7 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 格式化复数根的虚部:sqrt(-delta)/(2a)
|
/// 格式化复数根的虚部:sqrt(-delta)/(2a)
|
||||||
String _formatImaginaryPart(String sqrtExpr, double denominator) {
|
String _formatImaginaryPart(String sqrtExpr, double denominator) {
|
||||||
@@ -1256,33 +1347,6 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
|||||||
return coeffs;
|
return coeffs;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 规范化系数字符串
|
|
||||||
String _normalizeCoefficientString(String coeff) {
|
|
||||||
if (coeff.isEmpty || coeff == '+') return '1';
|
|
||||||
if (coeff == '-') return '-1';
|
|
||||||
|
|
||||||
// 处理类似 "2sqrt(3)" 的情况
|
|
||||||
coeff = coeff.replaceAll(' ', ''); // 移除空格
|
|
||||||
|
|
||||||
// 检查是否是纯数字
|
|
||||||
final numValue = double.tryParse(coeff);
|
|
||||||
if (numValue != null) {
|
|
||||||
return coeff;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否包含 sqrt
|
|
||||||
if (coeff.contains('sqrt(') || coeff.contains('\\sqrt{')) {
|
|
||||||
// 如果前面没有数字系数,默认为 1
|
|
||||||
if (coeff.startsWith('sqrt(') || coeff.startsWith('\\sqrt{')) {
|
|
||||||
return coeff.startsWith('-') ? coeff : '1' + coeff;
|
|
||||||
}
|
|
||||||
// 如果前面有数字,保持原样
|
|
||||||
return coeff;
|
|
||||||
}
|
|
||||||
|
|
||||||
return coeff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 合并系数,保持符号形式
|
/// 合并系数,保持符号形式
|
||||||
String _combineCoefficients(String? existing, String newCoeff) {
|
String _combineCoefficients(String? existing, String newCoeff) {
|
||||||
if (existing == null || existing == '0') return newCoeff;
|
if (existing == null || existing == '0') return newCoeff;
|
||||||
|
16
pubspec.lock
16
pubspec.lock
@@ -145,6 +145,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.0.8"
|
version: "1.0.8"
|
||||||
|
equatable:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: equatable
|
||||||
|
sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.7"
|
||||||
fake_async:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -169,6 +177,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "7.0.1"
|
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:
|
flutter:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description: flutter
|
description: flutter
|
||||||
|
@@ -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
|
# 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
|
# 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.
|
# 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:
|
environment:
|
||||||
sdk: ^3.9.2
|
sdk: ^3.9.2
|
||||||
@@ -40,6 +40,7 @@ dependencies:
|
|||||||
go_router: ^16.2.1
|
go_router: ^16.2.1
|
||||||
url_launcher: ^6.3.2
|
url_launcher: ^6.3.2
|
||||||
rational: ^2.2.3
|
rational: ^2.2.3
|
||||||
|
fl_chart: ^0.66.1
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
@@ -54,5 +54,56 @@ void main() {
|
|||||||
true,
|
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: '应该提供复数根',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user