Juli中的任意精度算法

2024-06-28 15:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有人问过这个问题,但不是这样问的。对于lt&n;=10000平方根的程序,lt&n。在

我一直想在茱莉亚身上这样做,但我不知道怎么做。主要是因为它处理无理数(如果x不是完全平方,sqrt(x)是无理的,例如sqrt(2)=1.414213…)。所以我认为我不能使用rational类。在

这里说https://docs.julialang.org/en/latest/manual/integers-and-floating-point-numbers/#Arbitrary-Precision-Arithmetic-1Julia可以用大浮点来做任意精度的算术。它们似乎不够准确。在

我也尝试过使用PyCall和Python中的Decimals包(来自Julia),但是出现了一些奇怪的错误(如果有用的话,我可以发布它们)。在

这是我的Python程序。我的问题是朱莉娅怎么做?在

def continuedFractionSquareRoots():
''' 
  For each number up to 100, get the length of the continued fraction 
  of the square root for it.
'''

decimal.getcontext().prec = 210 # Need lots of precision for this problem.

continuedFractionLengths = []
for i in range(1, 101):

    # For perfect squares, the period is 0
    irrationalNumber = decimal.Decimal(i).sqrt()
    if irrationalNumber == int(irrationalNumber):
        continue        

    continuedFractionLength = 0
    while True:

        intPart = irrationalNumber.to_integral_exact(rounding=decimal.ROUND_FLOOR)
        if continuedFractionLength == 0:
            firstContinuedFractionTimes2 = int(intPart*2)

        continuedFractionLength += 1
        if intPart == firstContinuedFractionTimes2:
            # Have reached the 'period' end for this fraction
            break

        fractionalPart = irrationalNumber - intPart
        irrationalNumber = 1 / fractionalPart

continuedFractionLengths.append(continuedFractionLength)
return continuedFractionLengths

如你所见,我需要一种计算精确平方根的方法,同时也需要一种得到整数部分的方法。这些都是真的,除了很多很多的精度!在

我不想给茱莉亚回个小密码,因为我不想给我发一个小密码!但在这里,它起作用了。正如我在下面的评论中所说的,我使用setprecision函数将精度设置为一个较高的值,它可以工作。根据经验,我得到了711的值。在

^{pr2}$

所以不管怎样,用户2357112解决了,非常感谢。在


Tags: ofthelt程序forif精度sqrt
2条回答

user2357112的答案是问题的核心,也是这个问题的正确答案。在

然而,为了完成这一点,“如何让这个python脚本在julia中运行”这一“字面”问题本身就是一个有趣的问题,因为它并不像最初看起来的那样简单,因为this issue的缘故,所以我也将演示如何做到这一点。在

假设您的python脚本名为“试验品“在当前目录中(以及正确的import decimal语句等),下面是如何将其作为python模块导入并运行相关函数:

using PyCall
unshift!(PyVector(pyimport("sys")["path"]), ""); # as per https://github.com/JuliaPy/PyCall.jl#troubleshooting
testo = pyimport("testo");
testo[:oddPeriodSquareRoots]()  # will output '1322'

就像Python的一样十进制。十进制,可以配置Julia的BigFloat的精度:

setprecision(however_many_bits)

注意这是以位表示的,不像十进制。十进制,因为BigFloat不使用十进制。在

相关问题 更多 >