bisection_method.dart 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // tools/bisection_method.dart
  2. import 'package:flutter/material.dart';
  3. import 'package:provider/provider.dart';
  4. import '../symja.dart';
  5. class BisectionMethodPage extends StatefulWidget {
  6. @override
  7. _BisectionMethodPageState createState() => _BisectionMethodPageState();
  8. }
  9. class _BisectionMethodPageState extends State<BisectionMethodPage> {
  10. final TextEditingController _functionController = TextEditingController(text: 'x^3 - x - 2');
  11. final TextEditingController _aController = TextEditingController(text: '1');
  12. final TextEditingController _bController = TextEditingController(text: '2');
  13. final TextEditingController _toleranceController = TextEditingController(text: '0.0001');
  14. final TextEditingController _maxIterationsController = TextEditingController(text: '100');
  15. List<String> _iterations = [];
  16. String _result = '';
  17. bool _isCalculating = false;
  18. /// 用 Symja 求 f(x) 在 [x] 处的值。
  19. ///
  20. /// 表达式**直接交给 Symja 解析**(以前用 math_expressions:那是另一套语法、
  21. /// 另一套优先级,同一个式子可能"在这里算得出来、在别处又不对")。
  22. Future<double> _evaluateFunction(String function, double x) async {
  23. final session = context.read<SymjaSession>();
  24. final r = await session.compute('N[$function /. x -> $x]');
  25. // Symja 的 N[...] 输出可能带精度标记(形如 3.14`2.5),去掉再解析
  26. final cleaned = r.text.trim().replaceAll(RegExp(r'`[0-9.]*$'), '');
  27. final v = double.tryParse(cleaned);
  28. if (v == null) throw Exception('f($x) = ${r.text},不是数值');
  29. return v;
  30. }
  31. Future<void> _calculate() async {
  32. if (_isCalculating) return;
  33. setState(() {
  34. _isCalculating = true;
  35. _iterations.clear();
  36. _result = '';
  37. });
  38. try {
  39. double a = double.parse(_aController.text);
  40. double b = double.parse(_bController.text);
  41. double tolerance = double.parse(_toleranceController.text);
  42. int maxIterations = int.parse(_maxIterationsController.text);
  43. String function = _functionController.text;
  44. if (a >= b) {
  45. throw Exception('区间左端点必须小于右端点');
  46. }
  47. double fa = await _evaluateFunction(function, a);
  48. double fb = await _evaluateFunction(function, b);
  49. if (fa.isNaN || fb.isNaN) {
  50. throw Exception('函数在端点处计算失败,请检查表达式');
  51. }
  52. if (fa * fb > 0) {
  53. throw Exception('函数在区间两端点必须异号\nf(a) = $fa, f(b) = $fb');
  54. }
  55. int iteration = 0;
  56. double c = a;
  57. while ((b - a).abs() > tolerance && iteration < maxIterations) {
  58. c = (a + b) / 2;
  59. double fc = await _evaluateFunction(function, c);
  60. if (fc.isNaN) {
  61. throw Exception('迭代过程中函数计算失败');
  62. }
  63. if (!mounted) return;
  64. _iterations.add('迭代 ${iteration + 1}: a=${a.toStringAsFixed(6)}, b=${b.toStringAsFixed(6)}, c=${c.toStringAsFixed(6)}, f(c)=${fc.toStringAsFixed(6)}');
  65. if (fc.abs() < tolerance) {
  66. break;
  67. } else if (fa * fc < 0) {
  68. b = c;
  69. fb = fc;
  70. } else {
  71. a = c;
  72. fa = fc;
  73. }
  74. iteration++;
  75. }
  76. if (!mounted) return;
  77. setState(() {
  78. _result = '近似解: ${c.toStringAsFixed(8)}\n'
  79. '迭代次数: $iteration\n'
  80. '最终误差: ${(b - a).abs().toStringAsFixed(8)}';
  81. });
  82. } on SymjaException catch (e) {
  83. if (mounted) setState(() => _result = '错误: $e');
  84. } catch (e) {
  85. if (mounted) setState(() => _result = '错误: $e');
  86. } finally {
  87. if (mounted) setState(() => _isCalculating = false);
  88. }
  89. }
  90. void _clear() {
  91. setState(() {
  92. _functionController.text = 'x^3 - x - 2';
  93. _aController.text = '1';
  94. _bController.text = '2';
  95. _toleranceController.text = '0.0001';
  96. _maxIterationsController.text = '100';
  97. _iterations.clear();
  98. _result = '';
  99. });
  100. }
  101. @override
  102. Widget build(BuildContext context) {
  103. return Scaffold(
  104. appBar: AppBar(
  105. title: Text('二分法求根', style: TextStyle(color: Colors.black)),
  106. backgroundColor: Colors.white,
  107. elevation: 1,
  108. iconTheme: IconThemeData(color: Colors.black),
  109. ),
  110. body: SingleChildScrollView(
  111. padding: EdgeInsets.all(16),
  112. child: Column(
  113. crossAxisAlignment: CrossAxisAlignment.start,
  114. children: [
  115. Text(
  116. '二分法求方程近似解',
  117. style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.deepPurple),
  118. ),
  119. SizedBox(height: 16),
  120. Text(
  121. '使用方法:\n'
  122. '1. 输入函数表达式(支持: +, -, *, /, ^, sin, cos, tan, ln, e, sqrt 等)\n'
  123. '2. 输入有根区间 [a, b]\n'
  124. '3. 设置精度和最大迭代次数\n'
  125. '4. 点击计算获取近似解\n\n'
  126. '示例表达式:\n'
  127. '• x^3 - x - 2\n'
  128. '• sin(x) + cos(x)\n'
  129. '• e^x - 2\n'
  130. '• ln(x) + sqrt(x)',
  131. style: TextStyle(fontSize: 14, color: Colors.grey[600]),
  132. ),
  133. SizedBox(height: 20),
  134. // 函数输入
  135. _buildInputField('函数 f(x)', '例如: x^3 - x - 2', _functionController),
  136. SizedBox(height: 16),
  137. Row(
  138. children: [
  139. Expanded(child: _buildInputField('区间左端点 a', '1', _aController)),
  140. SizedBox(width: 16),
  141. Expanded(child: _buildInputField('区间右端点 b', '2', _bController)),
  142. ],
  143. ),
  144. SizedBox(height: 16),
  145. Row(
  146. children: [
  147. Expanded(child: _buildInputField('精度 tolerance', '0.0001', _toleranceController)),
  148. SizedBox(width: 16),
  149. Expanded(child: _buildInputField('最大迭代次数', '100', _maxIterationsController)),
  150. ],
  151. ),
  152. SizedBox(height: 24),
  153. // 按钮
  154. Row(
  155. children: [
  156. Expanded(
  157. child: ElevatedButton(
  158. onPressed: _isCalculating ? null : _calculate,
  159. style: ElevatedButton.styleFrom(
  160. backgroundColor: Colors.deepPurple,
  161. padding: EdgeInsets.symmetric(vertical: 16),
  162. ),
  163. child: _isCalculating
  164. ? SizedBox(height: 20, width: 20, child: CircularProgressIndicator(color: Colors.white))
  165. : Text('计算', style: TextStyle(fontSize: 16, color: Colors.white)),
  166. ),
  167. ),
  168. SizedBox(width: 16),
  169. Expanded(
  170. child: OutlinedButton(
  171. onPressed: _clear,
  172. style: OutlinedButton.styleFrom(
  173. padding: EdgeInsets.symmetric(vertical: 16),
  174. ),
  175. child: Text('清空', style: TextStyle(fontSize: 16)),
  176. ),
  177. ),
  178. ],
  179. ),
  180. SizedBox(height: 24),
  181. // 结果展示
  182. if (_result.isNotEmpty) ...[
  183. Container(
  184. width: double.infinity,
  185. padding: EdgeInsets.all(16),
  186. decoration: BoxDecoration(
  187. color: _result.contains('错误') ? Colors.red[50] : Colors.green[50],
  188. borderRadius: BorderRadius.circular(8),
  189. border: Border.all(color: _result.contains('错误') ? Colors.red : Colors.green),
  190. ),
  191. child: Text(
  192. _result,
  193. style: TextStyle(
  194. fontSize: 16,
  195. fontWeight: FontWeight.bold,
  196. color: _result.contains('错误') ? Colors.red[800] : Colors.green[800]
  197. ),
  198. ),
  199. ),
  200. SizedBox(height: 16),
  201. ],
  202. // 迭代过程
  203. if (_iterations.isNotEmpty) ...[
  204. Text('迭代过程:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
  205. SizedBox(height: 8),
  206. Container(
  207. height: 200,
  208. decoration: BoxDecoration(
  209. border: Border.all(color: Colors.grey[300]!),
  210. borderRadius: BorderRadius.circular(8),
  211. ),
  212. child: ListView.builder(
  213. itemCount: _iterations.length,
  214. itemBuilder: (context, index) {
  215. return Container(
  216. padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  217. decoration: BoxDecoration(
  218. border: index > 0 ? Border(top: BorderSide(color: Colors.grey[200]!)) : null,
  219. color: index % 2 == 0 ? Colors.grey[50] : Colors.white,
  220. ),
  221. child: Text(
  222. _iterations[index],
  223. style: TextStyle(fontSize: 12, fontFamily: 'Monospace'),
  224. ),
  225. );
  226. },
  227. ),
  228. ),
  229. ],
  230. ],
  231. ),
  232. ),
  233. );
  234. }
  235. Widget _buildInputField(String label, String hint, TextEditingController controller) {
  236. return Column(
  237. crossAxisAlignment: CrossAxisAlignment.start,
  238. children: [
  239. Text(label, style: TextStyle(fontWeight: FontWeight.bold)),
  240. SizedBox(height: 4),
  241. TextField(
  242. controller: controller,
  243. decoration: InputDecoration(
  244. hintText: hint,
  245. border: OutlineInputBorder(),
  246. contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  247. ),
  248. ),
  249. ],
  250. );
  251. }
  252. }