简体   繁体   English

如何在C ++中进行32位十进制浮点数乘法?

[英]How to do 32 digit decimal floating point number multiplication in C++?

I have two numbers which are 32 digit decimal floating point numbers, like 1.2345678901234567890123456789012, I want to get the multiplication which is also 32 digit decimal floating point number. 我有两个数字,它们是32位十进制浮点数,例如1.2345678901234567890123456789012,我想获得也是32位十进制浮点数的乘法。 Is there any efficient way to do this? 有什么有效的方法可以做到这一点吗?

Just use boost::multiprecision . 只需使用boost::multiprecision You can use arbitrary precision but there is a typedef cpp_bin_float_50 which is a float with 50 decimal places. 您可以使用任意精度,但是有一个typedef cpp_bin_float_50 ,它是一个带有50个小数位的float

Example for multiplying to big decimal numbers: 乘以大十进制数字的示例:

#include <iostream>
#include <boost/multiprecision/cpp_bin_float.hpp>

int main(){
  boost::multiprecision::cpp_bin_float_50 val1("1.2345678901234567890123456789012");
  boost::multiprecision::cpp_bin_float_50 val2("2.2345678901234567890123456789012");  
  std::cout <<  std::setprecision(std::numeric_limits< boost::multiprecision::cpp_bin_float_50>::max_digits10);
  std::cout << val1*val2 << std::endl;
}

Output: 输出:

2.7587257654473404640618808351577828416864868162811293

Use the usual grade school algorithm (long multiplication). 使用通常的小学算法(长乘法)。 If you used 3 ints (instead of 4): 如果您使用3个整数(而不是4个):

A2A1A0 * B2B1B0 = A2*B2 A2*B1 A2*B0
                        A1*B2 A1*B1 A1*B0
                              A0*B2 A0*B1 A0*B0

Every multiplication will have a 2-int result. 每次乘法都会得到2整数的结果。 You have to sum every column on the right side, and propagate carry. 您必须对右侧的每一列求和,并传播进位。 In the end, you'll have a 6-int result (if inputs are 4-int, then the result is 8-int). 最后,您将得到一个6整数的结果(如果输入为4整数,则结果为8整数)。 You can then round this 8-int result. 然后,您可以舍入该8位数的结果。 This is how you can handle the mantissa part. 这就是处理尾数部分的方式。 The exponents should just be added together. 指数应只加在一起。

I recommend you to divide a problem into two parts: 我建议您将问题分为两个部分:

  1. multiplying a long number with an int 将整数与整数相乘
  2. adding the result from 1. into the final result 将结果从1.添加到最终结果

You'll need something like this as a workhorse (note that this code assumes that int is 32-bit, long long is 64-bit): 您将需要像下面这样的工作(注意,此代码假定int是32位,long long是64位):

void wideMul(unsigned int &hi, unsigned int &lo, unsigned int a, unsigned int b) {
    unsigned long long int r = (unsigned long long int)a*b;
    lo = (unsigned int)r;
    hi = (unsigned int)(r>>32);
}

Note: that if you had larger numbers, there are faster algorithms. 注意:如果您的数字较大,则可以使用更快的算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM