pragma solidity =0.5.16; /** * @title Math 数学计算库 * @notice 提供各种数学运算函数 * @dev 包含最小值计算和平方根计算等工具函数 */ library Math { /** * @notice 返回两个数中的较小值 * @param x 第一个数 * @param y 第二个数 * @return z 较小的数 */ function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } /** * @notice 计算平方根(巴比伦算法) * @dev 使用巴比伦方法计算平方根,参考: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method * @param y 需要计算平方根的数 * @return z 平方根结果 */ function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; // 迭代逼近,直到找到最优解 while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // 如果y为0,则z保持为0(默认值) } }