开发者

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]

how to obtain the best approximate fraction for a real number in mathematica

Here are the first 8 convergents for Sqrt[2]:

approximate[Sqrt[2]]

how to obtain the best approximate fraction for a real number in mathematica

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜