math_util.h File Reference
`#include <stdint.h>`

Go to the source code of this file.

## Functions

template<typename T >
rescale (T aNumerator, T aValue, T aDenominator)
Function rescale() More...

template<typename T >
int sign (T val)

template<>
int rescale (int aNumerator, int aValue, int aDenominator)

template<>
int64_t rescale (int64_t aNumerator, int64_t aValue, int64_t aDenominator)

static int round_nearest (double v)

## Function Documentation

template<typename T >
 T rescale ( T aNumerator, T aValue, T aDenominator )

Function rescale()

Scales a number (value) by rational (numerator/denominator). Numerator must be <= denominator.

Definition at line 38 of file math_util.h.

Referenced by sign().

39 {
40  return aNumerator * aValue / aDenominator;
41 }
template<>
 int rescale ( int aNumerator, int aValue, int aDenominator )

Definition at line 32 of file math_util.cpp.

33 {
34  return (int) ( (int64_t) aNumerator * (int64_t) aValue / (int64_t) aDenominator );
35 }
template<>
 int64_t rescale ( int64_t aNumerator, int64_t aValue, int64_t aDenominator )

Definition at line 39 of file math_util.cpp.

References abs, i, and sign().

40 {
41 #ifdef __x86_64__
42  return ( (__int128_t) aNumerator * (__int128_t) aValue ) / aDenominator;
43 #else
44  int64_t r = 0;
45  int64_t sign = ( ( aNumerator < 0 ) ? -1 : 1 ) * ( aDenominator < 0 ? -1 : 1 ) *
46  ( aValue < 0 ? -1 : 1 );
47
48  int64_t a = std::abs( aNumerator );
49  int64_t b = std::abs( aValue );
50  int64_t c = std::abs( aDenominator );
51
52  r = c / 2;
53
54  if( b <= INT_MAX && c <= INT_MAX )
55  {
56  if( a <= INT_MAX )
57  return sign * ( ( a * b + r ) / c );
58  else
59  return sign * ( a / c * b + ( a % c * b + r ) / c);
60  }
61  else
62  {
63  uint64_t a0 = a & 0xFFFFFFFF;
64  uint64_t a1 = a >> 32;
65  uint64_t b0 = b & 0xFFFFFFFF;
66  uint64_t b1 = b >> 32;
67  uint64_t t1 = a0 * b1 + a1 * b0;
68  uint64_t t1a = t1 << 32;
69  int i;
70
71  a0 = a0 * b0 + t1a;
72  a1 = a1 * b1 + ( t1 >> 32 ) + ( a0 < t1a );
73  a0 += r;
74  a1 += a0 < (uint64_t)r;
75
76  for( i = 63; i >= 0; i-- )
77  {
78  a1 += a1 + ( ( a0 >> i ) & 1 );
79  t1 += t1;
80
81  if( (uint64_t) c <= a1 )
82  {
83  a1 -= c;
84  t1++;
85  }
86  }
87
88  return t1 * sign;
89  }
90 #endif
91 }
#define abs(a)
Definition: auxiliary.h:84
size_t i
Definition: json11.cpp:597
int sign(T val)
Definition: math_util.h:44
 static int round_nearest ( double v )
inlinestatic

Definition at line 56 of file math_util.h.

57 {
58  return int( v < 0 ? v - 0.5 : v + 0.5 );
59 }
template<typename T >
 int sign ( T val )

Definition at line 44 of file math_util.h.

References rescale().

45 {
46  return ( T( 0 ) < val) - ( val < T( 0 ) );
47 }