【发布时间】:2019-06-18 13:39:17
【问题描述】:
我已经实现了在 2D 空间中查找点的极坐标的代码。如果该点位于第一或第二象限,0<=theta<=pi,如果它位于第三或第四象限,-pi <= theta <= 0。
module thetalib
contains
real function comp_theta( x1, x2)
implicit none
real , intent(in) :: x1, x2
real :: x1p, x2p
real :: x1_c=0.0, x2_c=0.0
real :: pi=4*atan(1.0)
x1p = x1 - x1_c
x2p = x2 - x2_c
! - Patch
!if ( x1p == 0 .and. x2p /= 0 ) then
! comp_theta = sign(pi/2.0, x2p)
!else
! comp_theta = atan ( x2p / x1p )
!endif
comp_theta = atan( x2p / x1p)
if ( x1p >= 0.0 .and. x2p >= 0.0 ) then
comp_theta = comp_theta
elseif ( x1p < 0 .and. x2p >= 0.0 ) then
comp_theta = pi + comp_theta
elseif( x1p < 0.0 .and. x2p < 0.0 ) then
comp_theta = -1* (pi - comp_theta)
elseif ( x1p >= 0.0 .and. x2p < 0.0 ) then
comp_theta = comp_theta
endif
return
end function comp_theta
end module thetalib
program main
use thetalib
implicit none
! Quadrant 1
print *, "(0.00, 1.00): ", comp_theta(0.00, 1.00)
print *, "(1.00, 0.00): ", comp_theta(1.00, 0.00)
print *, "(1.00, 1.00): ", comp_theta(1.00, 1.00)
! Quadrant 2
print *, "(-1.00, 1.00): ", comp_theta(-1.00, 1.00)
print *, "(-1.00, 0.00): ", comp_theta(-1.00, 0.00)
! Quadrant 3
print *, "(-1.00, -1.00): ", comp_theta(-1.00, -1.00)
! Quadrant 4
print *, "(0.00, -1.00): ", comp_theta(0.00, -1.00)
print *, "(1.00, -1.00): ", comp_theta(1.00, -1.00)
end program main
在函数thetalib::comp_theta 中,当除以零且分子为+ve 时,fortran 将其计算为-infinity,当分子为-ve 时,将其计算为+infinity(参见输出)
(0.00, 1.00): -1.570796
(1.00, 0.00): 0.0000000E+00
(1.00, 1.00): 0.7853982
(-1.00, 1.00): 2.356194
(-1.00, 0.00): 3.141593
(-1.00, -1.00): -2.356194
(0.00, -1.00): 1.570796
(1.00, -1.00): -0.7853982
这让我很困惑。我还实施了您看到的补丁来解决它。为了进一步调查,我设置了一个小测试:
program main
implicit none
real :: x1, x2
x1 = 0.0 - 0.0 ! Reflecting the x1p - 0.0
x2 = 1.0
write(*,*) "x2/x1=", x2/x1
x2 = -1.0
write(*,*) "x2/x1=", x2/x1
end program main
计算结果为:
x2/x1= Infinity
x2/x1= -Infinity
我的 fortran 版本:
$ ifort --version
ifort (IFORT) 19.0.1.144 20181018
Copyright (C) 1985-2018 Intel Corporation. All rights reserved.
我有三个问题:
- 为什么会有有符号的无限值?
- 标志是如何确定的?
- 为什么
infinity使用thetalib::comp_theta和测试程序的输出中显示的符号?
【问题讨论】:
-
使用
atan2(y,x)函数不是比自己旋转更容易吗? -
@Steve 是的,对于这种特殊情况,但我想知道为什么标志不匹配。
-
你是在问为什么会有有符号的无限值,为什么每个都是短测试的结果,或者如何避免它们?
-
@francescalus 是的,(a)为什么有有符号的无限值? (b) 符号是如何确定的——无论是在简短的测试用例中还是在
thetalib::comp_theta?如何避免将遵循 (a) 和 (b) 的答案。将编辑问题以反映这一点。 -
@IAmNerd2000 我尝试使用
x1 = 0.0 - 0.0行中的测试程序复制它,但结果不同。限制也是我想到的第一件事,但我无法重现它。
标签: fortran intel-fortran