Oracle® Developer Studio 12.5:数值计算指南

退出打印视图

更新时间: 2016 年 6 月
 
 

示例

此附录提供如何完成一些常见任务的示例。这些示例使用 Fortran 或 ANSI C 编写,多数依赖于 libmlibsunmath 的当前版本。这些示例已在 Oracle Solaris 10 Update 10 OS 或更高版本上使用 Oracle Developer Studio 12.5 进行了测试。C 示例是使用 –lsunmath –lm 选项编译的。

A.1 IEEE 运算

以下示例显示了一种检查浮点数的十六进制表示形式的方法。请注意,您还可以使用调试器来查找已存储数据的十六进制表示形式。

以下 C 程序输出双精度的近似 ?? 值,以及单精度无穷大:

示例 6  双精度示例
#include <math.h>
#include <sunmath.h>
 
int main() {
 union {
   float         flt;
   unsigned     un;
 } r;
 union {
   double      dbl;
   unsigned    un[2];
 } d;
 
 /* double precision */
 d.dbl = M_PI;
 (void) printf("DP Approx pi = %08x %08x = %18.17e \n",
     d.un[0], d.un[1], d.dbl);
 
 /* single precision */
 r.flt = infinityf();
 (void) printf("Single Precision %8.7e : %08x \n", 
     r.flt, r.un);
 
 return 0;
}

在基于 SPARC 的系统上,使用 –lsunmath 编译时,上述程序的输出如下所示:

DP Approx pi = 400921fb 54442d18 = 3.14159265358979312e+00 
Single Precision Infinity: 7f800000 

以下 Fortran 程序分别以两种格式输出最小的正规数:

示例 7  分别以两种格式输出最小的正归数(续)
 program print_ieee_values
c
c the purpose of the implicit statements is to ensure
c that the floatingpoint pseudo-intrinsic functions
c are declared with the correct type
c
 implicit real*16 (q)
 implicit double precision (d)
 implicit real (r)
 real*16           z
 double precision  x
 real              r
c
 z = q_min_normal()
 write(*,7) z, z
 7 format('min normal, quad: ',1pe47.37e4,/,' in hex ',z32.32)
c
 x = d_min_normal()
 
 write(*,14) x, x
 14 format('min normal, double: ',1pe23.16,' in hex ',z16.16)
c
 r = r_min_normal()
 write(*,27) r, r
 27 format('min normal, single: ',1pe14.7,' in hex ',z8.8)
c
 end

在基于 SPARC 的系统上,对应的输出显示如下:

min normal, quad:   3.3621031431120935062626778173217526026E-4932
 in hex 00010000000000000000000000000000
min normal, double:  2.2250738585072014-308 in hex 0010000000000000
min normal, single:  1.1754944E-38 in hex 00800000