rippled
ripple
basics
MathUtilities.h
1
//------------------------------------------------------------------------------
2
/*
3
This file is part of rippled: https://github.com/ripple/rippled
4
Copyright (c) 2020 Ripple Labs Inc.
5
6
Permission to use, copy, modify, and/or distribute this software for any
7
purpose with or without fee is hereby granted, provided that the above
8
copyright notice and this permission notice appear in all copies.
9
10
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
*/
18
//==============================================================================
19
20
#ifndef RIPPLE_BASICS_MATHUTILITIES_H_INCLUDED
21
#define RIPPLE_BASICS_MATHUTILITIES_H_INCLUDED
22
23
#include <
algorithm
>
24
#include <
cassert
>
25
#include <
cstddef
>
26
27
namespace
ripple
{
28
43
constexpr
std::size_t
44
calculatePercent
(
std::size_t
count,
std::size_t
total)
45
{
46
assert(total != 0);
47
return
((
std::min
(count, total) * 100) + total - 1) / total;
48
}
49
50
// unit tests
51
static_assert(
calculatePercent
(1, 2) == 50);
52
static_assert(
calculatePercent
(0, 100) == 0);
53
static_assert(
calculatePercent
(100, 100) == 100);
54
static_assert(
calculatePercent
(200, 100) == 100);
55
static_assert(
calculatePercent
(1, 100) == 1);
56
static_assert(
calculatePercent
(1, 99) == 2);
57
static_assert(
calculatePercent
(6, 14) == 43);
58
static_assert(
calculatePercent
(29, 33) == 88);
59
static_assert(
calculatePercent
(1, 64) == 2);
60
static_assert(
calculatePercent
(0, 100
'000'
000) == 0);
61
static_assert(
calculatePercent
(1, 100
'000'
000) == 1);
62
static_assert(
calculatePercent
(50
'000'
000, 100
'000'
000) == 50);
63
static_assert(
calculatePercent
(50
'000'
001, 100
'000'
000) == 51);
64
static_assert(
calculatePercent
(99
'999'
999, 100
'000'
000) == 100);
65
66
}
// namespace ripple
67
68
#endif
algorithm
cstddef
ripple::calculatePercent
constexpr std::size_t calculatePercent(std::size_t count, std::size_t total)
Calculate one number divided by another number in percentage.
Definition:
MathUtilities.h:44
std::min
T min(T... args)
ripple
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition:
RCLCensorshipDetector.h:29
cassert
std::size_t
Generated by
1.8.17