gpt4 book ai didi

MySQL float 类型范围和精度混淆

转载 作者:可可西里 更新时间:2023-11-01 08:03:19 25 4
gpt4 key购买 nike

我正在学习 MySQL,但对 float 的范围和精度有疑问。

来自mannual :

For FLOAT, the SQL standard permits an optional specification of the precision (but not the range of the exponent) in bits following the keyword FLOAT in parentheses. MySQL also supports this optional precision specification, but the precision value is used only to determine storage size. A precision from 0 to 23 results in a 4-byte single-precision FLOAT column. A precision from 24 to 53 results in an 8-byte double-precision DOUBLE column.

我使用这个命令创建了一个表

create table test (f_a float(23));

我有 4 个困惑:

  1. 手册中但不是指数范围是什么意思?
  2. 我可以毫无问题地执行 insert into test values (1e38);。即使我键入 38 数字,它仍然有效。但是 39 数字或 1e39 将失败。那么这个38是什么意思呢?
  3. 如何检查f_a 的类型转换?当我执行 desc test;f_a 的类型仍然是 float 即使我插入了一个 38 数字那一栏。
  4. 那么,范围精度到底有什么区别?

最佳答案

IEEE 浮点表示法并不是 MySQL 独有的。它遵循随处使用的相同标准。

1) 忽略长度说明符,那只是噪音。在 MySQL 中,正好有两种 float 据类型:单精度(32 位)和 double (64 位)。

该可选长度说明符只是提供了另一种指定 DOUBLE 的方法。

 alter table t add foo FLOAT(4), add bar FLOAT(40) ;

相当于

 alter table t add foo FLOAT  , add bar DOUBLE ; 

2) 1e38 中的 38 是 10 的指数次方,等价于

1.0 x 10^38

在不深入研究所有细节的情况下, float 本质上表示为

   sign * mantissa  * (radix ^ exponent)

例如,在 base10 中,我们可以这样表示值 123.45:

    +1  * 0.12345   * ( 10 ^ 3 )

或者,我们可以使用 base2,并表示一个值(介于 0 和 1 之间)乘以 2 的某个幂。

3) 1e39 (1.0*10^39) 大于IEEE单精度FLOAT所能表达的取值范围。 (“最大可表示的 IEEE 754 浮点值是 2 * 2^−23 * 2^27,大约是 3.402x10^38。

DOUBLE 精度 float 支持更大范围的值,最高可达 10^308。

4) range 是从最小值到最大值。对于 DOUBLE,范围是从 -1 * 10^30810^308

精度 基本上是可以表示的位数 的数量。对于单精度 FLOAT,我们得到大约 7 位十进制数字的精度。对于 DOUBLE,我们的精度是它的两倍,即 15 位小数。

--

IEEE float 并不是 MySQL 独有的。几乎所有现代处理器都包含对 float 进行运算的浮点运算单元。

引用资料:

https://en.wikipedia.org/wiki/Single-precision_floating-point_format

https://en.wikipedia.org/wiki/Double-precision_floating-point_format

关于MySQL float 类型范围和精度混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com