rippled
Loading...
Searching...
No Matches
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
27namespace ripple {
28
43constexpr std::size_t
45{
46 assert(total != 0); // NOTE No XRPL_ASSERT here, because constexpr
47 return ((std::min(count, total) * 100) + total - 1) / total;
48}
49
50// unit tests
51static_assert(calculatePercent(1, 2) == 50);
52static_assert(calculatePercent(0, 100) == 0);
53static_assert(calculatePercent(100, 100) == 100);
54static_assert(calculatePercent(200, 100) == 100);
55static_assert(calculatePercent(1, 100) == 1);
56static_assert(calculatePercent(1, 99) == 2);
57static_assert(calculatePercent(6, 14) == 43);
58static_assert(calculatePercent(29, 33) == 88);
59static_assert(calculatePercent(1, 64) == 2);
60static_assert(calculatePercent(0, 100'000'000) == 0);
61static_assert(calculatePercent(1, 100'000'000) == 1);
62static_assert(calculatePercent(50'000'000, 100'000'000) == 50);
63static_assert(calculatePercent(50'000'001, 100'000'000) == 51);
64static_assert(calculatePercent(99'999'999, 100'000'000) == 100);
65
66} // namespace ripple
67
68#endif
T min(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:25
constexpr std::size_t calculatePercent(std::size_t count, std::size_t total)
Calculate one number divided by another number in percentage.