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">
|
||||
<application
|
||||
android:label="simple_math_calc"
|
||||
android:label="SimpleMathCalc"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/launcher_icon">
|
||||
<activity
|
||||
|
@@ -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(
|
||||
signed: true,
|
||||
decimal: true,
|
||||
)
|
||||
: TextInputType.number,
|
||||
keyboardType: TextInputType.numberWithOptions(
|
||||
signed: true,
|
||||
decimal: true,
|
||||
),
|
||||
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> {
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 4),
|
||||
child: Text(
|
||||
'函数图像',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
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,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildToolbar() {
|
||||
return Material(
|
||||
elevation: 8,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
spacing: 8,
|
||||
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('^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,
|
||||
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('收起键盘'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
220
lib/solver.dart
220
lib/solver.dart
@@ -277,10 +277,9 @@ class SolverService {
|
||||
|
||||
final deltaDouble = delta.toDouble();
|
||||
if (deltaDouble > 0) {
|
||||
// Keep sqrt symbolic instead of evaluating to decimal
|
||||
final sqrtDeltaStr = _formatSqrtExpression(delta.toDouble());
|
||||
final x1Expr = _formatQuadraticRoot(-b, sqrtDeltaStr, 2 * a, true);
|
||||
final x2Expr = _formatQuadraticRoot(-b, sqrtDeltaStr, 2 * a, false);
|
||||
// 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(
|
||||
@@ -319,8 +318,9 @@ class SolverService {
|
||||
),
|
||||
);
|
||||
|
||||
// Keep sqrt symbolic for complex roots
|
||||
final sqrtNegDeltaStr = _formatSqrtExpression(-delta.toDouble());
|
||||
// For complex roots, we need to handle -delta
|
||||
final negDelta = -delta;
|
||||
final sqrtNegDeltaStr = _formatSqrtFromRational(negDelta);
|
||||
final realPart = -b / (2 * a);
|
||||
final imagPartExpr = _formatImaginaryPart(sqrtNegDeltaStr, 2 * a);
|
||||
|
||||
@@ -1079,81 +1079,172 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
||||
|
||||
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
|
||||
|
||||
/// 格式化平方根表达式,保持符号形式
|
||||
String _formatSqrtExpression(double value) {
|
||||
if (value == 0) return '0';
|
||||
/// 格式化 Rational 值的平方根表达式,保持符号形式
|
||||
String _formatSqrtFromRational(Rational value) {
|
||||
if (value == Rational.zero) return '0';
|
||||
|
||||
// 处理负数(用于复数根)
|
||||
if (value < 0) {
|
||||
return '\\sqrt{${(-value).toInt()}}';
|
||||
if (value < Rational.zero) {
|
||||
return '\\sqrt{${(-value).toBigInt()}}';
|
||||
}
|
||||
|
||||
// 检查是否为完全平方数
|
||||
final sqrtValue = sqrt(value);
|
||||
final rounded = sqrtValue.round();
|
||||
if ((sqrtValue - rounded).abs() < 1e-10) {
|
||||
return rounded.toString();
|
||||
}
|
||||
// 尝试将 Rational 转换为完全平方数的形式
|
||||
// 例如: 4/9 -> 2/3, 9/4 -> 3/2, 25/16 -> 5/4 等
|
||||
|
||||
// 寻找最大的完全平方数因子
|
||||
int maxSquareFactor = 1;
|
||||
int intValue = value.toInt();
|
||||
for (int i = 2; i * i <= intValue; i++) {
|
||||
if (intValue % (i * i) == 0) {
|
||||
maxSquareFactor = i * i;
|
||||
// 首先简化分数
|
||||
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}';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final coefficient = sqrt(maxSquareFactor).round();
|
||||
final remaining = intValue ~/ maxSquareFactor;
|
||||
|
||||
if (remaining == 1) {
|
||||
return coefficient == 1
|
||||
? '\\sqrt{$intValue}'
|
||||
: '$coefficient\\sqrt{$remaining}';
|
||||
} else if (coefficient == 1) {
|
||||
return '\\sqrt{$remaining}';
|
||||
// 处理根号部分
|
||||
if (remainingNumerator == BigInt.one &&
|
||||
remainingDenominator == BigInt.one) {
|
||||
// 没有根号部分
|
||||
if (result.isEmpty) {
|
||||
return '1';
|
||||
}
|
||||
} else if (remainingNumerator == remainingDenominator) {
|
||||
// 根号部分约分后为1
|
||||
if (result.isEmpty) {
|
||||
return '1';
|
||||
}
|
||||
} else {
|
||||
return '$coefficient\\sqrt{$remaining}';
|
||||
// 需要根号
|
||||
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,
|
||||
String sqrtExpr,
|
||||
Rational delta,
|
||||
double denominator,
|
||||
bool isPlus,
|
||||
) {
|
||||
final sign = isPlus ? '+' : '-';
|
||||
final bStr = b == 0
|
||||
? ''
|
||||
: b > 0
|
||||
? '${b.toInt()}'
|
||||
: '(${b.toInt()})';
|
||||
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{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{2}'
|
||||
: '-\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{2}';
|
||||
return isPlus ? '\\frac{$sqrtExpr}{2}' : '-\\frac{$sqrtExpr}{2}';
|
||||
} else {
|
||||
return isPlus
|
||||
? '\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{$denomStr}'
|
||||
: '-\\frac{\\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}}{$denomStr}';
|
||||
? '\\frac{$sqrtExpr}{$denomStr}'
|
||||
: '-\\frac{$sqrtExpr}{$denomStr}';
|
||||
}
|
||||
} else {
|
||||
// 完整的表达式:(-b ± sqrt(delta))/denominator
|
||||
final numerator = b > 0
|
||||
? '-$bStr $sign \\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}'
|
||||
: '(${b.toInt()}) $sign \\sqrt{${sqrtExpr.replaceAll('\\sqrt{', '').replaceAll('}', '')}}';
|
||||
final bInt = b.toInt();
|
||||
|
||||
if (denominator == 2) {
|
||||
return '\\frac{$numerator}{2}';
|
||||
// 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 {
|
||||
return '\\frac{$numerator}{$denomStr}';
|
||||
// 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}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1256,33 +1347,6 @@ ${b1}y &= ${c1 - a1 * x.toDouble()}
|
||||
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) {
|
||||
if (existing == null || existing == '0') return newCoeff;
|
||||
|
16
pubspec.lock
16
pubspec.lock
@@ -145,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:
|
||||
@@ -169,6 +177,14 @@ packages:
|
||||
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
|
||||
|
@@ -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
|
||||
@@ -40,6 +40,7 @@ dependencies:
|
||||
go_router: ^16.2.1
|
||||
url_launcher: ^6.3.2
|
||||
rational: ^2.2.3
|
||||
fl_chart: ^0.66.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
@@ -54,5 +54,56 @@ void main() {
|
||||
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