开发者

php sqrt function that returns an integer?

I'm creating a simple PHP program that does an action if (and only if) three random numbers compute to an integer. The random numbers are all integers, created with the rand() function. Without going into the specific details of the computation, the important thing (in terms of my problem) is that it includes the taking of a square root. Not being a very experienced PHP coder, the only square root function I know is sqrt(). The problem is, sqrt() returns a float, even when the input is an integer and output is exact. I briefly thought about converting the output to an integer (using something like intval(), but that won't work because that will convert all outputs to integers, making the tes开发者_如何学运维t useless! Any ideas on how to do this? Thanks,


If you just want to determine if it is a perfect square, just determine if the

intval(result) * intval(result) == originalValue

I don't know the php version of those functions, but perhaps you do? :)


That is a common problem when working with floating point. Just check that the float you get is very close to an integer; commonly this is done by checking that the fractional part is very small:

if (abs(round(f)-f))<delta)
  # do stuff

Here delta is a small constant, such as 0.0001. How small it must be depends on how close you expect your result to be to an integer. That will depend on your calculations.


Something along the lines of if($result % 1.0 == 0) might work, but I don't have the capability to test it right now.


$result % 1e9 will return an integer part of $result (for negatives it will find the ceil of result). But it is a hack, so you might use it only for fun.

https://repl.it/Chqm/1


This knowledge is from programming in another language but have you tried to multiply the expression by 1. for example if you needed to get the integer of something like

a = 3.45 * 8;

do this

a = 3.45 * 8 * 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜