在某些情况下,acos(1)返回NAN [英] acos(1) returns NAN in some conditions
本文介绍了在某些情况下,acos(1)返回NAN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
<?php
$lat1 = 35.697959;
$lat2 = 35.697959;
$lon1 = 139.707085;
$lon2 = 139.707085;
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
var_dump($dist); // returns 1
$dist = acos($dist);
var_dump($dist); // returns NAN
从注释中可以看到,
计算后$dist
等于1
,但是当我应用acos()
时,它返回NAN
.
As you can see from the comments, $dist
is equal to 1
after the calculation, but when I apply acos()
it returns NAN
.
如果我尝试手动复制它,则效果很好:
If I try to replicate it manually, it works just fine:
$x = 1;
$x = acos($x);
var_dump($x); // returns 0 as expected
这是怎么回事,我该如何解决?
What's going on here and how can I fix it?
在线外壳中的代码与此相同,因此您可以看到它实际上返回了这些值.>
Here's the same code in an online shell, so you can see that it actually returns those values.
推荐答案
找到了解决方案.看来问题与精度有关.如果我确定$dist
在[-1,1]
范围内,则可以正常运行:
Found the solution. It seems that the problem is related to precision. If I make sure that $dist
is within [-1,1]
range, it works fine:
$dist = acos(min(max($dist,-1.0),1.0));
工作示例: https://3v4l.org/dlunK
这篇关于在某些情况下,acos(1)返回NAN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文