Fortran 中的实数与整数
我有一个程序,它循环一个变量并在每一步计算一个值:
program cpout
implicit none
!declarations
integer, parameter :: dp = selected_real_kind(15)
! kind value for double precision
real(dp), parameter :: Ru = 8.314472_dp
real(dp) :: cp
integer :: loT, hiT, i
real(dp) :: iT
real(dp),dimension(14) :: ic8a
real(dp) :: ic8t
real(dp) :: ic8c
loT = 300
hiT = 3000
! ic8a is populated using a subroutine call
! I have checked, it reads in reals as it is supposed to
do i = loT, hiT, 1
iT = real(i,dp)
if (iT > ic8t) then
ic8c = Ru*(ic8a(1) + ic8a(2)*iT + ic8a(3)*(iT**2)
* + ic8a(4)*(iT**3) + ic8a(5)*(iT**4))
else
ic8c = Ru*(ic8a(8) + ic8a(9)*iT + ic8a(10)*(iT**2)
* + ic8a(11)*(iT**3) + ic8a(12)*(iT**4))
end if
end do
end program cpout
在我的第一次尝试中,我使用 iT 作为整数循环计数器,然后直接在公式中使用它。这产生了 iT
> 的分段图。 ic8t。当我添加 i
作为计数器,并在公式中使用它之前将 iT
转换为实数时,图表显示出应有的平滑效果。为什么在代入公式时,iT
是实数还是整数很重要?我的编译器是g77。
编辑:该公式给出了一些不准确的值 iT
< ic8t 也是如此。
I have a program which loops over one variable and computes a value at each step:
program cpout
implicit none
!declarations
integer, parameter :: dp = selected_real_kind(15)
! kind value for double precision
real(dp), parameter :: Ru = 8.314472_dp
real(dp) :: cp
integer :: loT, hiT, i
real(dp) :: iT
real(dp),dimension(14) :: ic8a
real(dp) :: ic8t
real(dp) :: ic8c
loT = 300
hiT = 3000
! ic8a is populated using a subroutine call
! I have checked, it reads in reals as it is supposed to
do i = loT, hiT, 1
iT = real(i,dp)
if (iT > ic8t) then
ic8c = Ru*(ic8a(1) + ic8a(2)*iT + ic8a(3)*(iT**2)
* + ic8a(4)*(iT**3) + ic8a(5)*(iT**4))
else
ic8c = Ru*(ic8a(8) + ic8a(9)*iT + ic8a(10)*(iT**2)
* + ic8a(11)*(iT**3) + ic8a(12)*(iT**4))
end if
end do
end program cpout
In my first attempt, I used iT
as the integer loop counter, and then used it directly in the formula. This produced a piecewise graph for iT
> ic8t
. When I added i
as the counter, and converted iT
to real before using it in the formula, the graph came out smooth as it should. Why should it matter whether iT
is real or integer when plugging in to the formula? My compiler is g77.
EDIT: The formula gives some inaccurate values for iT
< ic8t
as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只使用 INTEGER 变量
i
(正如您在评论中提到的),您可能会出现算术溢出。您可以像以前一样将i
转换为 REAL,或者选择适当的种类参数为它。一个小例子:If you just use INTEGER variable
i
(as you mentioned in your comment) you probably have arithmetic overflow. You can either converti
to REAL as you did or choose an appropriate kind parameter for it. A small example: