algorithmmatlabnumerical-analysis

How to find nth digit of an irrational number of the form $\sqrt(x)$


I'm writing a matlab code which uses digits of an irrational number. I tried finding it using a taylor expansion of $\sqrt(1+x)$. Since division to large numbers could be a bad idea for Matlab, this method seems to me not a good one.

I wonder if there is any simpler and efficient method to do this?


Solution

  • If you have the Symbolic Toolbox, vpa does that. You can specify the number of significant digits you want:

    x = '2'; %// define x as a *string*. This avoids loss of precision
    n = 100; %// desired number of *significant* digits
    result = vpa(['sqrt(' x ')'], n);
    

    The result is a symbolic variable. If needed, convert to a string:

    result = char(result);
    

    In the example above,

    result =
    1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573
    

    Note that this is subject to rounding. For example, the result with n = 7 is 1.414214 instead of 1.414213.

    In newer Matlab versions (tested on R2017b), using a char input with vpa is discouraged, and support for this may be removed in the future. The recommended approach is to first define the variable as symbolic, and then apply the required operations to it:

    x = sym(2);
    n = 100;
    result = vpa(sqrt(x), n);