File: Utility.cpp

package info (click to toggle)
ausaxs 1.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 72,592 kB
  • sloc: cpp: 49,853; ansic: 6,901; python: 730; makefile: 18
file content (67 lines) | stat: -rw-r--r-- 1,722 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-License-Identifier: LGPL-3.0-or-later
// Author: Kristian Lytje

#include <utility/Utility.h>
#include <utility/Console.h>

using namespace ausaxs;

bool utility::approx(double v1, double v2, double abs, double eps) {
    return std::abs(v1 - v2) <= std::max(abs, eps * std::max(std::abs(v1), std::abs(v2)));
}

bool utility::equal(double a, double b, double c) {
    return a == b && b == c;
}

std::string utility::uid() {
    static unsigned int i = 0;
    return std::to_string(i++);
}

std::string utility::uid(const std::string& s) {return s + uid();}

std::ostream& utility::detail::operator<<(std::ostream& os, const __dummy& obj) {
    os << obj.s;
    return os;
}

std::string utility::round(double val, unsigned int decimals) noexcept {
    std::stringstream ss;
    ss << std::fixed << std::setprecision(decimals) << val;
    return ss.str();
}

utility::detail::__dummy utility::fixedwidth(double number, unsigned int width) {
    std::string s = std::to_string(number);
    // remove unnecessary 0s
    unsigned int end = s.size();
    for (unsigned int i = end; i > 0; i--) {
        if (s[i-1] != '0') {
            end = i+1;
            break;
        }
    }
    if (end < s.size()) {
        s.resize(end);
    }

    std::string o;
    for (unsigned int i = 0; i < width; i++) {
        if (i < s.size()) {
            o += s[i];
        } else {
            o += ' ';
        }
    }

    // check how lossy the conversion was
    #ifdef DEBUG
        double d = std::stod(o);
        if (!approx(d, number, 1e-3)) {
            console::print_warning("Fixed-width conversion of " + std::to_string(number) + " to " + o + " is lossy.");
        }
    #endif
    
    return {std::move(o)};
}