在某次面试中被问到,发现自己并不能解释清楚这个看似基础的问题。
浮点数如何表示
根据 IEEE.754 标准,我们用以下公式来表示 float
和 double
。
各变量的 bits 数如下:
type | sign | exponent | fraction |
---|---|---|---|
float | 1 | 8 | 23 |
double | 1 | 11 | 52 |
但是每个区域的表示并不是简单的二进制直接转换,以表示 0.15625 为例。
float in bits- 首先我们 sign 是 0, 表示正数
- exponent 是
- fraction 是
因此,结果是
exponent 的表示需要减去127。
fraction 的表示类似于二进制的小数定义(以 2 为底)。比如,十进制里的 0.11 实质上是 。二进制里则应该是 。
浮点数精度
知道浮点数表示方法后,精度就是 fraction 部分外加符号位能表示的精度,即:
例如:
- 比 1 小的最大数字
0 01111110 11111111111111111111111 = 3f7f ffff
- 1
0 01111111 00000000000000000000000 = 3f80 0000
- 比 1 大的最小数字
0 01111111 00000000000000000000001 = 3f80 0001
整型和浮点型运算速度
曾经自己想当然认为浮点型运算比整形慢,实验发现并不一定:
#include <iostream>
#include <chrono>
template<typename T>
void calculate(T x, T y, int count) {
while (count != 0) {
T a = x + y;
T b = x - y;
T c = x * y;
T d = x / y;
--count;
}
}
int main(int argc, char const *argv[]) {
const auto t1 = std::chrono::steady_clock::now();
int count = std::numeric_limits<int>::max() / 2;
calculate(2, 3, count);
const auto t2 = std::chrono::steady_clock::now();
calculate(1.3, 1.5, count);
const auto t3 = std::chrono::steady_clock::now();
std::cout << "int calculation: " <<
std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count()
<< "us" << std::endl;
std::cout << "float calculation: " <<
std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count()
<< "us" << std::endl;
return 0;
}
结果是:
int calculation: 2879312us
float calculation: 1974401us
所以这个结论不成立。
为何 GPU 更擅长计算浮点数
cpu设计的目的其实更偏向高速的通用计算,既包括逻辑运算又包括数学运算。因此设计成功能齐全,但是运算核心较少。现在主流 CPU 只有 4 核。
gpu设计的目的是图形加速,也就是对每个像素点(非常多)进行简单的并行运算。因此设计成结构简单,但是运算核心非常多。例如,GTX1080系列显卡有 2560 个核心。
网友评论