0

in scala, given the integers d & x, I would have a boolean expression which should be true if and only if y = (x^2 - 1) / d^2 is a square.

I tried this:

(Math.sqrt((x * x - 1) / (d * d)).toInt * Math.sqrt((x * x - 1) / (d * d)).toInt == ((x * x - 1) / (d * d)))

but the 3-tuple (x = 2, d = <all values tested>, y = 0.0) seems to be always an answer of my problem, which is obviously wrong. I think my error comes from the rounding made: if x=2, d=4 (for example) then x * x - 1 == 3 and d * d == 16 so the division leads to 0.

do you know what is the good expression?

4

2 回答 2

1

如果 n 是圆形正方形,则 Math.sqrt(n).toInt == Math.sqrt(n)。在你的情况下:

(Math.sqrt((x * x - 1) / (d * d)).toInt == Math.sqrt((x * x - 1) / (d * d)))

但在此之前,您需要确保 x 和 d 是doubles。在 REPL 中尝试:

scala> val x = 1
scala> val d = 3
scala> x/d

Int 除以 Int 将得到四舍五入的 Int,因此您将 sqrt 应用为零。

同样由于浮点运算,您可能希望像这样进行比较:

(Math.sqrt((x * x - 1) / (d * d)).toInt - Math.sqrt((x * x - 1) / (d * d))) <= ZERO

其中零被一个非常小的数字代替,比如 0.00001

于 2013-09-28T11:49:41.420 回答
0

因为这是整数除法,所以您正在检查是否((x*x-1)/(d*d)).toInt是一个完美的正方形。您可以先将所有内容都转换为双精度数,但如果您想留在整数领域,请检查除法是否应产生整数:

( x*x-1 % d*d == 0 ) && Math.sqrt(y).toInt == Math.sqrt(y)
于 2013-09-29T04:10:14.163 回答