跳到正文

题解

题解:UVA12413 Big Decimal Calculator

stripe_python约 28 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 28 分钟
获赞
7
题目
UVA12413

版本

  1. v1当前

本题解基于笔者的 BigInteger 2.6 项目编写。

结构

考虑基于大整数实现高精度实数。具体地,笔者参考了著名论文《理性愉悦——高精度数值计算(2012WC)》中的内容:

记 num=v×10enum=v \times 10^e。这里,vv 使用已实现的压位大整数,ee 是指数。实现上,设计了一个管理器,保证所有大整数的 ee 相同。

C++
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 类型设计如下:

C++
#include "BigInteger.h"

class BigDecimal {
private:
	BigInteger val;
	int e;  // *this = val * 10^e
}

输入

简单的字符串处理工作。

C++
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);
}
C++
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;
}

输出

字符串大模拟。笔者实现了向上、向下取整、四舍五入、五舍六入的模式:

C++
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);}

四则运算

加减法:

v1×10e±v2×10e=(v1±v2)×10ev_1 \times 10^e \pm v_2 \times 10^e = (v_1 \pm v_2) \times 10^e

乘法:

v1×10e×v2×10e=v1v2×102ev_1 \times 10^e \times v_2 \times 10^e = v_1v_2 \times 10^{2e}

除法:

v1×10ev2×10e=v1×10ev2×10n×10e−n≈⌊v1v2×10n⌋×10n\dfrac{v_1 \times 10^e}{v_2 \times 10^e}=\dfrac{v_1 \times 10^e}{v_2 \times 10^n \times 10^{e-n}}\approx \lfloor \dfrac{v_1}{v_2 \times 10^n} \rfloor \times 10^n

这里取 nn 为整数 v2v_2 的位数。结果的指数需要调整到 ee。

C++
// 调整指数
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;
}
C++
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;
}

比大小

有手就行。

C++
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

各种科学运算

exp⁡\exp

由泰勒展开得:

ex=∑i=0+∞xii!e^x = \sum_{i=0}^{+ \infty} \dfrac{x^i}{i!}
C++
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;
}

ln⁡\ln

这里笔者不会了(泰勒收敛过慢),参考了 tiger2005 大神的方法。

先将 xx 不断除以 22,记录次数并乘 ln⁡(2)\ln(2) 作为初始答案。

当 0.75≤x≤1.50.75 \le x \le 1.5 时,使用

ln⁡(1+t1−t)=2∑k=1+∞t2k−12k−1\ln(\dfrac{1+t}{1-t})=2 \sum_{k=1}^{+\infty} \dfrac{t^{2k - 1}}{2k-1}

其中

x=1+t1−tx=\dfrac{1+t}{1-t}

解得

t=1−x1+xt=\dfrac{1-x}{1+x}
C++
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;
}

sqrt⁡\operatorname{sqrt}

笔者参考了论文中的方法,比直接小数牛迭快。

⌊v×10e⌋=⌊v×10n×10e−n⌋≈⌊v×10n⌋×10e−n2\lfloor \sqrt{v \times 10^e} \rfloor=\lfloor \sqrt{v \times 10^n \times 10^{e-n}} \rfloor \approx \lfloor \sqrt{v \times 10^n } \rfloor \times {10^{\frac{e-n}{2}}}

这里 nn 为 vv 的位数。若 e−ne-n 为奇数,则还需再左移一位。

C++
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;
}

整数开方使用牛顿迭代法。

C++
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;
}

pow⁡\operatorname{pow}

ab=eln⁡a×ba^b=e^{\ln a \times b}

三角函数

由泰勒展开得:

sin⁡x=∑k=0+∞(−1)kx2k+1(2k+1)!\sin x = \sum_{k=0}^{+\infty} (-1)^k \dfrac{x^{2k+1}}{(2k+1)!} cos⁡x=∑k=0+∞(−1)kx2k(2k)!\cos x = \sum_{k=0}^{+\infty} (-1)^k \dfrac{x^{2k}}{(2k)!}

然后

tan⁡x=sin⁡xcos⁡x\tan x =\dfrac{\sin x} {\cos x}

不过要注意根据 xx 的正负性分类讨论。

这里笔者把 cos⁡x\cos x 当成了奇函数,debug 1h。

还有实现一个取模,根据周期性把 xx 放到 [0,2π)[0, 2\pi) 里面。

C++
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();}

反三角函数

arctan⁡x=∑k=0+∞(−1)kx2k+12k+1\arctan x = \sum^{+\infty}_{k=0} (-1)^k \dfrac{x^{2k+1}}{2k+1}

由于 xx 很大,需要使用

arctan⁡x=2arctan⁡x2+1−1x\arctan x=2\arctan \dfrac{\sqrt{x^2+1}-1}{x}

将 ∣x∣|x| 快速缩小。

另有:

arcsin⁡x=arctan⁡x1−x2arccos⁡x=12π−arcsin⁡x\arcsin x = \arctan \dfrac{x}{\sqrt{1-x^2}}\\ \arccos x = \dfrac{1}{2} \pi - \arcsin x
C++
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;
}

atan2atan2 套公式即可。

C++
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();
}

实现细节

可以初始化一些常量方便计算。

C++
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;

同时实现一些科学函数的其他版本:

C++
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 的最终代码,放到剪贴板里了。

AC Code

广告

BigInteger 项目

BigDecimal 项目

原文