how to obtain the best approximate fraction for a real number in mathematica
If I want to obtain the best approximate fraction/rational for a given real number 开发者_运维技巧and the specificied maximum denominator as an integer, how to do this in mathematica? Many thanks.
Convergents of continued fractions offer a useful method for getting better and better fractional representations of an irrational number. I've also found them helpful for understanding connections to other ideas by way of the Euclidean algorithm.
Let's use convergents to approximate pi and the square root of two.
ClearAll[approximate];
approximate[r_, nConvergents_: 8, precision_: 10] :=
With[{c = Convergents[ContinuedFraction[r, nConvergents]]},
TableForm[Transpose[{c, N[r - c, precision]}],
TableHeadings -> {None, {Row[{"approximation of ", r}], "error"}}]]
Here's are the first 8 convergents for pi:
approximate[Pi]
Here are the first 8 convergents for Sqrt[2]
:
approximate[Sqrt[2]]
The successive error terms shrink and alternate direction as convergence advances.
In approximate
, you can optionally specify the number of convergents and precision desired.
Enjoy.
Here's some additional documentation about continued fractions, including some lovely demonstrations.
Look at Help for Rationalize
. RootApproximant
can be also useful
精彩评论