否定浮点数是否总是安全的 [英] Is it always safe to negate a floating point number

查看:79
本文介绍了否定浮点数是否总是安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

double f = foo();
double g = -f;

其中foo()可以返回分配给f的任何内容.

where foo() can return anything that be assigned to f.

double g = -f;在C和C ++中安全吗?对于IEEE 754类型,显然是,但是C和C ++并不将浮点实现限制于此(与Java不同).

is double g = -f; safe in C and C++? For IEEE 754 types it obviously is but C and C++ do not restrict floating point implementation to that (unlike Java).

如果安全的话,-g是否总是将truefoo()进行比较?

If it is safe, then would -g always compare true with foo()?

(以上情况不适用于2补码中的int).

(The above is not true for int in 2's complement).

推荐答案

浮点类型由C标准的5.2.4.2.2节定义(至少是草稿N1570):

Floating types are defined by §5.2.4.2.2 of the C standard (draft N1570 at least):

浮点类型的特征是根据模型来定义的,该模型描述了浮点数和值的表示形式,这些浮点数和值提供了有关实现的浮点算法的信息.21)以下参数用于为每个浮点数定义模型浮点类型:

The characteristics of floating types are defined in terms of a model that describes a representation of floating-point numbers and values that provide information about an implementation’s floating-point arithmetic.21) The following parameters are used to define the model for each floating-point type:

  • s符号(±1)
  • b指数表示形式的基数或基数(整数> 1)
  • e指数(最小emin和最大emax之间的整数)
  • p精度(有效位中的基数b的位数)
  • fk小于b(有效数字)的非负整数
  • s sign (±1)
  • b base or radix of exponent representation (an integer > 1)
  • e exponent (an integer between a minimum emin and a maximum emax)
  • p precision (the number of base-b digits in the significand)
  • fk nonnegative integers less than b (the significand digits)

浮点数(x)由以下模型定义:

A floating-point number (x) is defined by the following model:

所以是的,该表达式是有点 安全,但在foo返回的值中未指定的其他种类的浮点数"之一的情况下,标准:

So yes, that expression is somewhat safe, except in the case where foo returned one of the "other kinds of floating point numbers" not specified by the standard:

除了归一化的浮点数(如果x≠0,f1> 0)之外,浮点类型还可以包含其他种类的浮点数,例如非正规浮点数(x≠0, e = emin,f1 = 0)和未归一化的浮点数(x≠0,e> emin,f1 = 0),以及非浮点数的值,例如无穷大和NaN.

In addition to normalized floating-point numbers ( f1 > 0 if x ≠ 0), floating types may be able to contain other kinds of floating-point numbers, such as subnormal floating-point numbers (x ≠ 0, e = emin, f1 = 0) and unnormalized floating-point numbers (x ≠ 0, e > emin, f1 = 0), and values that are not floating-point numbers, such as infinities and NaNs.

和:

实现可能会给零和非浮点数的值(例如infinities和NaN)加一个符号或使它们保持无符号状态.

An implementation may give zero and values that are not floating-point numbers (such as infinities and NaNs) a sign or may leave them unsigned.

对此可能还有其他警告,但是该标准在有关这些类型的特征的详细信息中做了很多说明.您可以在此公开草案中阅读有关它们的所有信息.

There are probably other caveats to this, but the standard goes in a fair bit of details about the characteristics of these types. You can read all about them in this publicly available draft.

这篇关于否定浮点数是否总是安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆