ClickHouse

Форк
0
/
multiplyDecimal.cpp 
134 строки · 5.0 Кб
1
#include <Functions/FunctionsDecimalArithmetics.h>
2
#include <Functions/FunctionFactory.h>
3

4
namespace DB
5
{
6

7
namespace ErrorCodes
8
{
9
    extern const int DECIMAL_OVERFLOW;
10
}
11

12
namespace
13
{
14

15
struct MultiplyDecimalsImpl
16
{
17
    static constexpr auto name = "multiplyDecimal";
18

19
    template <typename FirstType, typename SecondType>
20
    static inline Decimal256
21
    execute(FirstType a, SecondType b, UInt16 scale_a, UInt16 scale_b, UInt16 result_scale)
22
    {
23
        if (a.value == 0 || b.value == 0)
24
            return Decimal256(0);
25

26
        Int256 sign_a = a.value < 0 ? -1 : 1;
27
        Int256 sign_b = b.value < 0 ? -1 : 1;
28

29
        std::vector<UInt8> a_digits = DecimalOpHelpers::toDigits(a.value * sign_a);
30
        std::vector<UInt8> b_digits = DecimalOpHelpers::toDigits(b.value * sign_b);
31

32
        std::vector<UInt8> multiplied = DecimalOpHelpers::multiply(a_digits, b_digits);
33

34
        UInt16 product_scale = scale_a + scale_b;
35
        while (product_scale < result_scale)
36
        {
37
            multiplied.push_back(0);
38
            ++product_scale;
39
        }
40

41
        while (product_scale > result_scale&& !multiplied.empty())
42
        {
43
            multiplied.pop_back();
44
            --product_scale;
45
        }
46

47
        if (multiplied.empty())
48
            return Decimal256(0);
49

50
        if (multiplied.size() > DecimalUtils::max_precision<Decimal256>)
51
            throw DB::Exception(ErrorCodes::DECIMAL_OVERFLOW, "Numeric overflow: result bigger that Decimal256");
52

53
        return Decimal256(sign_a * sign_b * DecimalOpHelpers::fromDigits(multiplied));
54
    }
55
};
56

57
}
58

59
REGISTER_FUNCTION(MultiplyDecimals)
60
{
61
    factory.registerFunction<FunctionsDecimalArithmetics<MultiplyDecimalsImpl>>(FunctionDocumentation{
62
        .description=R"(
63
Performs multiplication on two decimals. Result value will be of type [Decimal256](../../sql-reference/data-types/decimal.md).
64
Result scale can be explicitly specified by `result_scale` argument (const Integer in range `[0, 76]`). If not specified, the result scale is the max scale of given arguments.
65

66
:::note
67
These functions work significantly slower than usual `multiply`.
68
In case you don't really need controlled precision and/or need fast computation, consider using [multiply](#multiply)
69
:::
70

71
**Syntax**
72

73
```sql
74
multiplyDecimal(a, b[, result_scale])
75
```
76

77
**Arguments**
78

79
-   `a` — First value: [Decimal](../../sql-reference/data-types/decimal.md).
80
-   `b` — Second value: [Decimal](../../sql-reference/data-types/decimal.md).
81
-   `result_scale` — Scale of result: [Int/UInt](../../sql-reference/data-types/int-uint.md).
82

83
**Returned value**
84

85
-   The result of multiplication with given scale.
86

87
Type: [Decimal256](../../sql-reference/data-types/decimal.md).
88

89
**Example**
90

91
```text
92
┌─multiplyDecimal(toDecimal256(-12, 0), toDecimal32(-2.1, 1), 1)─┐
93
│                                                           25.2 │
94
└────────────────────────────────────────────────────────────────┘
95
```
96

97
**Difference from regular multiplication:**
98
```sql
99
SELECT toDecimal64(-12.647, 3) * toDecimal32(2.1239, 4);
100
SELECT toDecimal64(-12.647, 3) as a, toDecimal32(2.1239, 4) as b, multiplyDecimal(a, b);
101
```
102

103
```text
104
┌─multiply(toDecimal64(-12.647, 3), toDecimal32(2.1239, 4))─┐
105
│                                               -26.8609633 │
106
└───────────────────────────────────────────────────────────┘
107
┌─multiplyDecimal(toDecimal64(-12.647, 3), toDecimal32(2.1239, 4))─┐
108
│                                                         -26.8609 │
109
└──────────────────────────────────────────────────────────────────┘
110
```
111

112
```sql
113
SELECT
114
    toDecimal64(-12.647987876, 9) AS a,
115
    toDecimal64(123.967645643, 9) AS b,
116
    multiplyDecimal(a, b);
117
SELECT
118
    toDecimal64(-12.647987876, 9) AS a,
119
    toDecimal64(123.967645643, 9) AS b,
120
    a * b;
121
```
122

123
```text
124
┌─────────────a─┬─────────────b─┬─multiplyDecimal(toDecimal64(-12.647987876, 9), toDecimal64(123.967645643, 9))─┐
125
│ -12.647987876 │ 123.967645643 │                                                               -1567.941279108 │
126
└───────────────┴───────────────┴───────────────────────────────────────────────────────────────────────────────┘
127
Received exception from server (version 22.11.1):
128
Code: 407. DB::Exception: Received from localhost:9000. DB::Exception: Decimal math overflow: While processing toDecimal64(-12.647987876, 9) AS a, toDecimal64(123.967645643, 9) AS b, a * b. (DECIMAL_OVERFLOW)
129
```
130
)"});
131

132
}
133

134
}
135

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.