这有点被问到了,但不是这样。我有一个小 Python 程序,它可以找到 n (1 <= n <= 10000) 平方根的连分数。
我一直在尝试在 Julia 中做到这一点,但我不知道该怎么做。主要是因为它处理无理数(如果 x 不是完全平方,则 sqrt(x) 是无理数,例如 sqrt(2) = 1.414213...)。所以我认为我不能使用理性类。
它在这里说https://docs.julialang.org/en/latest/manual/integers-and-floating-point-numbers/#Arbitrary-Precision-Arithmetic-1 Julia 可以使用 BigFloats 进行任意精度算术。但它们似乎不够准确。
我也尝试在 Python 中使用 PyCall 和 Decimals 包(来自 Julia),但出现奇怪的错误(如果它们有帮助,我可以发布它们)。
这是我的 Python 程序。我的问题是如何在 Julia 中做到这一点?
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
如您所见,我需要一种计算精确平方根的方法,以及一种获取数字整数部分的方法。这就是真的,除了很多很多的精度!
伙计们,我没有发布我的 Julia 代码,因为我不想有一个小手稿来回答!但在这里,它有效。正如我在下面的评论中所说,我使用 setprecision 函数将精度设置为一个高值并且它可以工作。我凭经验得到了 711 的值。
setprecision(711)
function continuedFractionSquareRoots()
#=
For each number up to 100, get the length of the continued fraction
of the square root for it.
=#
continuedFractionLengths = Int[]
for i=1:100
# For perfect squares, the period is 0
irrationalNumber = BigFloat(sqrt(BigFloat(i)))
if irrationalNumber == floor(irrationalNumber)
continue
end
continuedFractionLength = 0
while true
intPart = floor(irrationalNumber)
if continuedFractionLength == 0
firstContinuedFractionTimes2 = intPart*2
end
continuedFractionLength += 1
if intPart == firstContinuedFractionTimes2
# Have reached the 'period' end for this fraction
break
end
fractionalPart = irrationalNumber - intPart
irrationalNumber = BigFloat(1) / fractionalPart
end
push!(continuedFractionLengths, continuedFractionLength)
end
return continuedFractionLengths
end
所以无论如何,user2357112解决了它,非常感谢。