本题解基于笔者的 BigInteger 2.6 项目编写。
结构
考虑基于大整数实现高精度实数。具体地,笔者参考了著名论文《理性愉悦——高精度数值计算(2012WC)》中的内容:
记 。这里, 使用已实现的压位大整数, 是指数。实现上,设计了一个管理器,保证所有大整数的 相同。
enum __round_types {
ROUND_CEIL, ROUND_FLOOR, ROUND_05, ROUND_04
};
int __global_precision = -65;
int __global_round_type = ROUND_04;
struct __Context {
void precision(int p) {__global_precision = p - 1;}
void round_type(__round_types t) {__global_round_type = t;}
} context;对 BigDecimal 类型设计如下:
#include "BigInteger.h"
class BigDecimal {
private:
BigInteger val;
int e; // *this = val * 10^e
}输入
简单的字符串处理工作。
static BigInteger move_l(const BigInteger& num, int x) {
std::string s = num.to_string();
for (int i = 1; i <= x; i++) s += '0';
return BigInteger(s);
}
static BigInteger move_r(const BigInteger& num, int x) {
std::string s = num.to_string();
for (int i = 1; i <= x && !s.empty(); i++) s.pop_back();
return BigInteger(s);
}BigDecimal& BigDecimal::operator= (const BigInteger& x) {
e = 0, val = x, trim();
return *this;
}
BigDecimal& BigDecimal::operator= (const BigDecimal& x) {
e = x.e, val = x.val, trim();
return *this;
}
BigDecimal& BigDecimal::operator= (const long double& x) {
std::stringstream ss; ss << std::setprecision(24) << x;
return *this = ss.str();
}
BigDecimal& BigDecimal::operator= (const std::string& s) {
e = 0, val = 0, trim();
if (s.empty()) return *this;
int n = s.size(), pos = 0, flag = 1;
while (pos < n && s[pos] == '-') flag = !flag, pos++;
std::string a, b;
while (pos < n && std::isdigit(s[pos])) a.push_back(s[pos]), pos++;
if (s[pos] != '.') {
val = a, e = 0;
if (!flag) val = -val;
return trim(), *this;
}
for (pos++; pos < n && std::isdigit(s[pos]); pos++) b.push_back(s[pos]);
e = -static_cast<long long>(b.size()), val = a + b;
if (!flag) val = -val;
return trim(), *this;
}输出
字符串大模拟。笔者实现了向上、向下取整、四舍五入、五舍六入的模式:
std::string BigDecimal::to_string_base(std::function<std::string(std::string&)> solve) const {
std::string res = val.to_string();
if (e == 0) return solve(res);
if (e > 0) {
for (int i = 1; i <= e; i++) res += '0';
return solve(res);
}
int n = res.size(), point = n + e;
if (point >= 0) {
res.insert(res.begin() + point, '.');
if (res[0] == '.') res = '0' + res;
if ((int) res.size() >= 2 && res[0] == '-' && res[1] == '.') res.insert(res.begin() + 1, '0');
return solve(res);
}
std::string pre = "0.";
for (int i = 1; i <= -point; i++) pre += '0';
pre += res;
return solve(pre);
}
std::string BigDecimal::to_string(int precision) const {
switch (__global_round_type) {
case ROUND_CEIL:
return ceil(precision);
case ROUND_FLOOR:
return floor(precision);
case ROUND_04:
return round_04(precision);
case ROUND_05:
return round_05(precision);
}
return "";
}
std::string BigDecimal::floor(int precision) const {
int p = precision != INT_MAX ? -precision + 1 : -__global_precision;
return to_string_base([&](std::string& s) -> std::string {
int pos = s.find('.');
if (pos == (int) std::string::npos) s += ".0", pos = s.find('.');
int n = s.size(), sep = n - pos;
if (sep == p) return s;
if (sep > p) {
for (int i = 1; i <= sep - p; i++) s.pop_back();
if (s.back() == '.') s.pop_back();
return s;
}
for (int i = 1; i <= p - sep; i++) s += '0';
return s;
});
}
std::string BigDecimal::ceil(int precision) const {
int p = precision != INT_MAX ? -precision + 2 : -__global_precision + 1;
return to_string_base([&](std::string& s) -> std::string {
int pos = s.find('.');
if (pos == (int) std::string::npos) s += ".0", pos = s.find('.');
int n = s.size(), sep = n - pos;
if (sep > p) {
for (int i = 1; i <= sep - p; i++) s.pop_back();
} else if (sep < p) {
for (int i = 1; i <= p - sep; i++) s += '0';
}
int i = s.size() - 1;
for (i--; s[i] == '.' || s[i] == '9'; i--) {
if (s[i] == '.') continue;
s[i] = '0';
if (i == 0) {
s.insert(s.begin(), '0');
break;
}
}
s[i]++, s.pop_back();
if (s.back() == '.') s.pop_back();
return s;
});
}
std::string BigDecimal::round_045(int precision, bool round04) const {
int p = precision != INT_MAX ? -precision + 2 : -__global_precision + 1;
return to_string_base([&](std::string& s) -> std::string {
int pos = s.find('.');
if (pos == (int) std::string::npos) s += ".0", pos = s.find('.');
int n = s.size(), sep = n - pos;
if (sep > p) {
for (int i = 1; i <= sep - p; i++) s.pop_back();
} else if (sep < p) {
for (int i = 1; i <= p - sep; i++) s += '0';
}
int i = s.size() - 1;
bool flag = round04 ? (s[i] >= '5') : (s[i] > '5');
if (flag) {
for (i--; s[i] == '.' || s[i] == '9'; i--) {
if (s[i] == '.') continue;
s[i] = '0';
if (i == 0) {
s.insert(s.begin(), '0');
break;
}
}
s[i]++;
}
s.pop_back();
if (s.back() == '.') s.pop_back();
return s;
});
}
std::string BigDecimal::round_04(int precision) const {return round_045(precision, true);}
std::string BigDecimal::round_05(int precision) const {return round_045(precision, false);}四则运算
加减法:
乘法:
除法:
这里取 为整数 的位数。结果的指数需要调整到 。
// 调整指数
void trim() {
const int p = __global_precision;
if (e < p) val = move_r(val, p - e);
else if (e > p) val = move_l(val, e - p);
e = p;
}BigDecimal& BigDecimal::operator+= (const BigDecimal& x) {
return trim(), val += x.val, *this;
}
BigDecimal& BigDecimal::operator-= (const BigDecimal& x) {
return trim(), val -= x.val, *this;
}
BigDecimal& BigDecimal::operator*= (const BigDecimal& x) {
return trim(), val *= x.val, e += x.e, trim(), *this;
}
BigDecimal& BigDecimal::operator/= (const BigDecimal& x) {
if (x.is_zero()) throw NaNError();
int n = x.len();
trim(), val = move_l(val, n), e -= n;
return val /= x.val, e -= x.e, trim(), *this;
}
BigDecimal BigDecimal::operator+ (const BigDecimal& x) const {
return BigDecimal(val + x.val, e);
}
BigDecimal BigDecimal::operator- (const BigDecimal& x) const {
return BigDecimal(val - x.val, e);
}
BigDecimal BigDecimal::operator* (const BigDecimal& x) const {
return BigDecimal(val * x.val, e + x.e);
}
BigDecimal BigDecimal::operator/ (const BigDecimal& x) const {
if (x.is_zero()) throw NaNError();
BigDecimal res = *this; res /= x; return res;
}比大小
有手就行。
int BigDecimal::compare(const BigDecimal& y) const {
if (is_zero() && y.is_zero()) return 0;
if (val < 0 && y.val > 0) return -1;
if (val > 0 && y.val < 0) return 1;
int sgn = 1;
if (val < 0 && y.val < 0) sgn = -1;
if (e != y.e) {
if (e < y.e) return -sgn;
return sgn;
}
if (val < y.val) return -sgn;
if (val > y.val) return sgn;
return 0;
}
bool BigDecimal::operator== (const BigDecimal& x) const {return compare(x) == 0;}
#if __cplusplus >= 202002L
auto BigDecimal::operator<=> (const BigDecimal& x) const {return compare(x);}
#else
bool BigDecimal::operator< (const BigDecimal& x) const {return compare(x) < 0;}
bool BigDecimal::operator> (const BigDecimal& x) const {return compare(x) > 0;}
bool BigDecimal::operator!= (const BigDecimal& x) const {return compare(x) != 0;}
bool BigDecimal::operator<= (const BigDecimal& x) const {return compare(x) <= 0;}
bool BigDecimal::operator>= (const BigDecimal& x) const {return compare(x) >= 0;}
#endif //__cplusplus >= 202002L各种科学运算
由泰勒展开得:
BigDecimal BigDecimal::exp() const {
__global_precision -= 2;
BigDecimal a = 1, res = 0, h = *this;
BigInteger k = 0, fac = 1;
while (true) {
BigDecimal b = a / fac;
if (b.is_zero()) break;
res += b, a *= h;
k++, fac *= k;
}
__global_precision += 2, res.reset();
return res;
}这里笔者不会了(泰勒收敛过慢),参考了 tiger2005 大神的方法。
先将 不断除以 ,记录次数并乘 作为初始答案。
当 时,使用
其中
解得
BigDecimal BigDecimal::ln() const {
if (*this < 1) return -((b_one / *this).ln());
// by tiger2005
__global_precision -= 2;
BigDecimal coef = 0, x = *this, ln2 = b_ln2, sqrt2 = b_sqrt2;
while (x > sqrt2) {
x.val = x.val.div2();
coef += ln2;
}
x = (x - 1) / (x + 1);
BigDecimal cnt = x * 2, res = cnt + coef;
x *= x;
for (int i = 3; ; i += 2) {
cnt *= x;
BigDecimal b = cnt / i;
if (b.is_zero()) break;
res += b;
}
__global_precision += 2, res.reset();
return res;
}笔者参考了论文中的方法,比直接小数牛迭快。
这里 为 的位数。若 为奇数,则还需再左移一位。
BigDecimal BigDecimal::sqrt() const {
BigDecimal x = *this;
int n = x.len();
x.val = move_l(x.val, n), x.e -= n;
if (x.e & 1) x.val = move_r(x.val, 1), x.e++;
x.val = x.val.sqrt(), x.e /= 2, x.trim();
return x;
}整数开方使用牛顿迭代法。
BigInteger BigInteger::sqrt() const {
if (*this <= 1) return *this;
static constexpr long long base = BigInteger::BASE;
BigInteger n = *this, x0 = BigInteger(base)._move_l((n.size + 2) >> 1);
BigInteger x = (x0 + n / x0).div2();
while (x < x0) std::swap(x, x0), x = (x0 + n / x0).div2();
return x0;
}三角函数
由泰勒展开得:
然后
不过要注意根据 的正负性分类讨论。
这里笔者把 当成了奇函数,debug 1h。
还有实现一个取模,根据周期性把 放到 里面。
BigDecimal& BigDecimal::operator%= (const BigDecimal& x) {
if (x.is_zero()) throw NaNError();
return *this -= x * (*this / x).to_bigint();
}
BigDecimal BigDecimal::operator% (const BigDecimal& x) const {
if (x.is_zero()) throw NaNError();
return *this - x * (*this / x).to_bigint();
}
BigDecimal BigDecimal::sin() const {
if (*this < 0) return -(abs().sin());
__global_precision -= 2;
BigDecimal x = *this, y = b_pi * 2;
x = (x % y + y) % y; BigDecimal val = x;
BigDecimal res = x, cur = x;
x *= x;
for (int i = 3; ; i += 2) {
cur = cur * x / (1LL * i * (i - 1));
if (cur.is_zero()) break;
cur = -cur, res += cur;
}
__global_precision += 2, res.reset();
return res;
}
BigDecimal BigDecimal::cos() const {
if (*this < 0) return abs().cos();
__global_precision -= 2;
BigDecimal x = *this, y = b_pi * 2;
x = (x % y + y) % y; BigDecimal val = x;
BigDecimal res = 1, cur = 1;
x *= x;
for (int i = 2; ; i += 2) {
cur = cur * x / (1LL * i * (i - 1));
if (cur.is_zero()) break;
cur = -cur, res += cur;
}
__global_precision += 2, res.reset();
return res;
}
BigDecimal BigDecimal::tan() const {return sin() / cos();}反三角函数
由于 很大,需要使用
将 快速缩小。
另有:
BigDecimal BigDecimal::asin() const {
BigDecimal x = *this;
return (x / (b_one - x * x).sqrt()).atan();
}
BigDecimal BigDecimal::acos() const {
return b_pi / 2 - asin();
}
BigDecimal BigDecimal::atan() const {
if (val < 0) return -(abs().atan());
BigDecimal x = *this;
if (x > 1) return b_pi / 2 - (b_one / x).atan();
if (x >= 0.1) return (x / ((x * x + 1).sqrt() + 1)).atan() * 2;
__global_precision -= 2, x = *this;
BigDecimal sgn = x, res = x;
x = -x * x;
for (int i = 3; ; i += 2) {
sgn *= x;
BigDecimal b = sgn / i;
if (b.is_zero()) break;
res += b;
}
__global_precision += 2, res.reset();
return res;
}套公式即可。
BigDecimal BigDecimal::atan2(const BigDecimal& x) const {
BigDecimal y = *this;
if (x > 0) return (y / x).atan();
if (y >= 0 && x < 0) return (y / x).atan() + b_pi;
if (y < 0 && x < 0) return (y / x).atan() - b_pi;
if (y > 0) return b_pi / 2;
if (y < 0) return -b_pi / 2;
throw NaNError();
}实现细节
可以初始化一些常量方便计算。
const BigDecimal b_pi = (std::string) "3.1415926535897932384626433832795028841971693993751058209749445923";
const BigDecimal b_ln2 = (std::string) "0.693147180559945309417232121458176568075500134360255254120680009";
const BigDecimal b_sqrt2 = (std::string) "1.4142135623730950488016887242096980785696718753769480731766797";
const BigDecimal b_one = 1;同时实现一些科学函数的其他版本:
BigDecimal b_exp(const BigDecimal& x) {return x.exp();}
BigDecimal b_ln(const BigDecimal& x) {return x.ln();}
BigDecimal b_sqrt(const BigDecimal& x) {return x.sqrt();}
BigDecimal b_pow(const BigDecimal& x, const BigDecimal& y) {return x.pow(y);}
BigDecimal b_abs(const BigDecimal& x) {return x.abs();}
BigDecimal b_sin(const BigDecimal& x) {return x.sin();}
BigDecimal b_cos(const BigDecimal& x) {return x.cos();}
BigDecimal b_tan(const BigDecimal& x) {return x.tan();}
BigDecimal b_asin(const BigDecimal& x) {return x.asin();}
BigDecimal b_acos(const BigDecimal& x) {return x.acos();}
BigDecimal b_atan(const BigDecimal& x) {return x.atan();}
BigDecimal b_atan2(const BigDecimal& y, const BigDecimal& x) {return y.atan2(x);}代码
综上,我们实现了一个支持多种科学运算的轻量级高精度小数库。不过 UVA 的代码限制是 30K,这里经过一些删减后得到了 29.6K 的最终代码,放到剪贴板里了。