2022-02-11 09:07:11 +11:00
|
|
|
/* SPDX-License-Identifier: GPL-2.0-or-later
|
|
|
|
|
* Copyright 2001-2002 NaN Holding BV. All rights reserved. */
|
2009-11-09 22:42:41 +00:00
|
|
|
|
2019-02-18 08:08:12 +11:00
|
|
|
/** \file
|
|
|
|
|
* \ingroup bli
|
2011-02-27 20:37:56 +00:00
|
|
|
*/
|
|
|
|
|
|
2009-11-09 22:42:41 +00:00
|
|
|
#include "BLI_math.h"
|
|
|
|
|
|
2013-12-06 03:46:27 +11:00
|
|
|
#include "BLI_strict_flags.h"
|
|
|
|
|
|
2015-04-24 11:37:48 +10:00
|
|
|
int pow_i(int base, int exp)
|
|
|
|
|
{
|
|
|
|
|
int result = 1;
|
|
|
|
|
BLI_assert(exp >= 0);
|
|
|
|
|
while (exp) {
|
|
|
|
|
if (exp & 1) {
|
|
|
|
|
result *= base;
|
|
|
|
|
}
|
|
|
|
|
exp >>= 1;
|
|
|
|
|
base *= base;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
2011-09-28 05:53:40 +00:00
|
|
|
double double_round(double x, int ndigits)
|
|
|
|
|
{
|
2021-12-09 20:01:44 +11:00
|
|
|
/* From Python 3.1 `floatobject.c`. */
|
|
|
|
|
|
2009-11-29 22:42:33 +00:00
|
|
|
double pow1, pow2, y, z;
|
|
|
|
|
if (ndigits >= 0) {
|
|
|
|
|
pow1 = pow(10.0, (double)ndigits);
|
|
|
|
|
pow2 = 1.0;
|
2012-03-25 12:41:58 +00:00
|
|
|
y = (x * pow1) * pow2;
|
2009-11-29 22:42:33 +00:00
|
|
|
/* if y overflows, then rounded value is exactly x */
|
2019-03-27 13:16:10 +11:00
|
|
|
if (!isfinite(y)) {
|
2009-11-29 22:42:33 +00:00
|
|
|
return x;
|
2019-03-27 13:16:10 +11:00
|
|
|
}
|
2009-11-29 22:42:33 +00:00
|
|
|
}
|
|
|
|
|
else {
|
|
|
|
|
pow1 = pow(10.0, (double)-ndigits);
|
|
|
|
|
pow2 = 1.0; /* unused; silences a gcc compiler warning */
|
|
|
|
|
y = x / pow1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
z = round(y);
|
2019-03-27 13:16:10 +11:00
|
|
|
if (fabs(y - z) == 0.5) {
|
2009-11-29 22:42:33 +00:00
|
|
|
/* halfway between two integers; use round-half-even */
|
2012-03-25 12:41:58 +00:00
|
|
|
z = 2.0 * round(y / 2.0);
|
2019-03-27 13:16:10 +11:00
|
|
|
}
|
2009-11-29 22:42:33 +00:00
|
|
|
|
2019-03-27 13:16:10 +11:00
|
|
|
if (ndigits >= 0) {
|
2009-11-29 22:42:33 +00:00
|
|
|
z = (z / pow2) / pow1;
|
2019-03-27 13:16:10 +11:00
|
|
|
}
|
|
|
|
|
else {
|
2009-11-29 22:42:33 +00:00
|
|
|
z *= pow1;
|
2019-03-27 13:16:10 +11:00
|
|
|
}
|
2009-11-29 22:42:33 +00:00
|
|
|
|
|
|
|
|
/* if computation resulted in overflow, raise OverflowError */
|
|
|
|
|
return z;
|
|
|
|
|
}
|
2020-11-13 16:58:14 +11:00
|
|
|
|
|
|
|
|
float floor_power_of_10(float f)
|
|
|
|
|
{
|
|
|
|
|
BLI_assert(!(f < 0.0f));
|
|
|
|
|
if (f != 0.0f) {
|
|
|
|
|
return 1.0f / (powf(10.0f, ceilf(log10f(1.0f / f))));
|
|
|
|
|
}
|
|
|
|
|
return 0.0f;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
float ceil_power_of_10(float f)
|
|
|
|
|
{
|
|
|
|
|
BLI_assert(!(f < 0.0f));
|
|
|
|
|
if (f != 0.0f) {
|
|
|
|
|
return 1.0f / (powf(10.0f, floorf(log10f(1.0f / f))));
|
|
|
|
|
}
|
|
|
|
|
return 0.0f;
|
|
|
|
|
}
|