首页 > 解决方案 > 有没有更好的方法来使用 Pari/GP 提取实数的数字?

问题描述

这是我当前的代码,但它很丑陋,我担心非常大或小的数字可能会出现边缘情况。有一个更好的方法吗?

real_to_int(n)={
    if(n==floor(n),return(floor(n)));   \\ If "n" is a whole number we're done
    my(v=Vec(strprintf("%g",n)));       \\ Convert "n" to a zero-padded character vector
    my(d=sum(i=1,#v,i*(v[i]==".")));    \\ Find the decimal point
    my(t=eval(concat(v[^d])));          \\ Delete the decimal point and reconvert to a number
    my(z=valuation(t,10));              \\ Count trailing zeroes
    t/=10^z;                            \\ Get rid of trailing zeroes
    return(t)
}

标签: pari-gp

解决方案


您可以将输入实数拆分为整数和小数部分,而无需查找点。

real_to_int(n) = {
    my(intpart=digits(floor(n)));
    my(fracpartrev=fromdigits(eval(Vecrev(Str(n))[1..-(2+#intpart)])));
    fromdigits(concat(intpart, Vecrev(digits(fracpartrev))))
};

real_to_int(123456789.123456789009876543210000)
> 12345678912345678900987654321

请注意,数字列表中所有前导零的组成digits和消除。fromdigits


推荐阅读