在用C双打二进制运算 [英] Binary operations on doubles in C

查看:181
本文介绍了在用C双打二进制运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的高速计算问题,为大规模的模拟。为了加快这一进程,我希望做一些优化,其中之一是计算仅在没有跳跃几个周期的双重的绝对值。

I'm working on a high speed computing problem for a large scale simulation. In order to speed up the process I wish to make a couple of optimizations, one of which is to compute the absolute value of a double in only a couple of cycles without jumps.

我的想法是,这64位双精度值重新用1位符号位,11位指数和52位尾数psented $ P $。因此,一个双值异或带着面具:
千万00000000 00000000 00000000将产生所期望的结果:

My idea was, that 64-Bit double values are represented with a 1-Bit sign Bit, an 11-Bit exponent and a 52-Bit Mantissa. So a double value XOR-ed with a mask: 10000000 00000000 00000000 00000000 would yield the desired result:

double abs(double x) {
    double mask = -0.0e0;
    return x^mask;
}

现在显然很少有一个原因需要对双打二进制运算,所以自然编译器会引发错误:

Now obviously there are few reason one would need binary operations on doubles, so naturally the compiler throws an error:

error: invalid operands to binary ^ (have ‘double’ and ‘double’)

我不知道是否有什么办法可以使在快时尚这个工作,因为我不希望整件事转换成字符数组,并早在别处被提出。这将那种打败快速计算的目的。

I was wondering whether there was any way to make this work in a fast fashion, since I didn't wish to convert the whole thing into a char-array and back as was suggested elsewhere. That would sort of defeat the purpose of fast computing.

我很感激所有帮助...

I'm thankful for all help...

推荐答案

在@Artur变化:结果
..配套使用大小的整数。结果
..工会初始化双。不是更快,但更紧了。

Variation on @Artur:
.. Use matching sized integer.
.. Initialize union with double. Not faster, but tighter.

#include <stdint.h>
double Abs_double(double d) {
  union {
    double d;
    uint64_t u64;
  } u = {d};
  u.u64 &= ~( (uint64_t) 1 << 63);
  return u.d;
}

请注意:我会留在晶圆厂()除非分析显示,其他解决方案快

Note: I'd stay with fabs() unless profiling showed other solutions faster.

这篇关于在用C双打二进制运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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