Horizon
math_util.h
1/*
2 * This program source code file is part of KICAD, a free EDA CAD application.
3 *
4 * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
5 * Copyright (C) CERN
6 * @author Tomasz Wlostowski <tomasz.wlostowski@cern.ch>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#ifndef __MATH_UTIL_H
27#define __MATH_UTIL_H
28
29#include <stdint.h>
30
37template <typename T>
38T rescale( T aNumerator, T aValue, T aDenominator )
39{
40 return aNumerator * aValue / aDenominator;
41}
42
43template <typename T>
44int sign( T val )
45{
46 return ( T( 0 ) < val) - ( val < T( 0 ) );
47}
48
49// explicit specializations for integer types, taking care of overflow.
50template <>
51int rescale( int aNumerator, int aValue, int aDenominator );
52
53template <>
54int64_t rescale( int64_t aNumerator, int64_t aValue, int64_t aDenominator );
55
56static inline int round_nearest( double v )
57{
58 return int( v < 0 ? v - 0.5 : v + 0.5 );
59}
60
61#endif // __MATH_UTIL_H