跳到正文

科技·工程

实现 cmath 的一部分

SClan_Official约 17 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 17 分钟

版本

  1. v1当前

主线

我们按照 cppreference 的顺序实现。

fabs 系列

关于 fabs 系列:非常好,我们一开始就遇到了问题。

fabsf,fabs 和 fabsl 是没有问题的,但是下面的 fabsd32,fabsd64 和 fabsd128 又怎么解决呢?

本来希望使用类似这样的东西解决:

C++
#if sizeof(float) == 32
using _Decimal32 = float;
#elif sizeof(double) == 32
using _Decimal32 = double;
#elif sizeof(long double) == 32
using _Decimal32 = long double;
#else
#error cannot find a float type that has 32 bits
#endif

结果发现 sizeof 并不能用在预处理命令中。

这个时候,我们就可以使用 <type_traits> 中的 conditional_t,但是我们的目标是不依赖任何其它库,并且 conditional_t 手写也不难,于是尝试手写,还可以实现一个更强大的东西。

支线 11

我们尝试实现一个 type_array<id, a0, a1, a2, ...>,访问 aid。

其实,不难。这样的技巧已经有很多了,网上一抓一大把,我也写了一篇(但没写完)简要介绍模板元编程的文章。

总之,我们可以这样:

C++
namespace mystl_std
{
	class mystl_error_type {/*something*/};
	template<unsigned id, typename t = mystl_error_type, typename ...types>
	class mystl_type_array { public: using type = mystl_type_array<id - 1, types...>::type; };
	template<typename t, typename ...types>
	class mystl_type_array<0, t, types...> { public: using type = t; };
	template<unsigned id>
	class mystl_type_array<id, mystl_error_type> { public: using type = mystl_error_type; };
}

算了还是解释一下吧,id 代表下标,下面的是模板特化,因为模板特化的优先级比较高,所以当 id = 0 时会采用第二个(直接使用 t),否则会使用下面的,使 id 减一,然后去除掉第一个元素。但是当后面都没有的时候,id 还不是 00,那么就会是 mystl_error_type,这样方便进行处理,不然直接 CE 掉了。

于是我们就可以愉快地实现了。

目前,我们的 mystl_error_type 是这样的:

C++
class mystl_error_type
{
	friend bool operator!=(mystl_error_type x, mystl_error_type y) { return false; }
	friend bool operator>=(mystl_error_type x, mystl_error_type y) { return true; }
	friend bool operator<=(mystl_error_type x, mystl_error_type y) { return true; }
	template<typename T>
	friend int operator<=>(mystl_error_type x, T y) { return 0; }
	friend mystl_error_type operator-(mystl_error_type x) { return x; }
};

因为有些机子不支持 128128 位的浮点类型,于是我们加上三个变量来表示各个位数的浮点类型是否支持。

这样,我们需要一个可以判断两个类型是否相同的模板类,也很简单。

所以:

C++
	template<typename a, typename b>
	class mystl_is_equal { public: static constexpr bool val = false; };
	template<typename a>
	class mystl_is_equal<a, a> { public: static constexpr bool val = true; };

回到 fabs 系列

一个常见的错误实现:

C++
	float mystl_fabsf(float x) { return x > 0 ? x : -x; }
	double mystl_fabs(double x) { return x > 0 ? x : -x; }
	long double mystl_fabsl(long double x) { return x > 0 ? x : -x; }
#ifdef __linux
	using mystl__Decimal32 = mystl_type_array<int(sizeof(float) >= 4) + int(sizeof(double) >= 4) + int(sizeof(long double) >= 4) - 1, long double, double, float>::type;
	using mystl__Decimal64 = mystl_type_array<int(sizeof(float) >= 8) + int(sizeof(double) >= 8) + int(sizeof(long double) >= 8) - 1, long double, double, float>::type;
	using mystl__Decimal128 = __float128;
#else
	using mystl__Decimal32 = mystl_type_array<int(sizeof(float) >= 4) + int(sizeof(double) >= 4) + int(sizeof(long double) >= 4) - 1, long double, double, float>::type;
	using mystl__Decimal64 = mystl_type_array<int(sizeof(float) >= 8) + int(sizeof(double) >= 8) + int(sizeof(long double) >= 8) - 1, long double, double, float>::type;
	using mystl__Decimal128 = mystl_type_array<int(sizeof(float) >= 16) + int(sizeof(double) >= 16) + int(sizeof(long double) >= 16) - 1, long double, double, float>::type;
#endif
	constexpr bool canuse_fabsd32 = !mystl_is_equal<mystl__Decimal32, mystl_error_type>::val;
	constexpr bool canuse_fabsd64 = !mystl_is_equal<mystl__Decimal64, mystl_error_type>::val;
	constexpr bool canuse_fabsd128 = !mystl_is_equal<mystl__Decimal128, mystl_error_type>::val;

	mystl__Decimal32 fabsd32(mystl__Decimal32 x) { return x > 0 ? x : -x; }
	mystl__Decimal64 fabsd64(mystl__Decimal64 x) { return x > 0 ? x : -x; }
	mystl__Decimal128 fabsd128(mystl__Decimal128 x) { return x > 0 ? x : -x; }

错因:0>00 > 0 不成立,所以会返回 −0-0。

正确实现:

C++
	float mystl_fabsf(float x) { return x < 0 ? -x : x; }
	double mystl_fabs(double x) { return x < 0 ? -x : x; }
	long double mystl_fabsl(long double x) { return x < 0 ? -x : x; }
#ifdef __linux
	using mystl__Decimal32 = mystl_type_array<int(sizeof(float) >= 4) + int(sizeof(double) >= 4) + int(sizeof(long double) >= 4) - 1, long double, double, float>::type;
	using mystl__Decimal64 = mystl_type_array<int(sizeof(float) >= 8) + int(sizeof(double) >= 8) + int(sizeof(long double) >= 8) - 1, long double, double, float>::type;
	using mystl__Decimal128 = __float128;
#else
	using mystl__Decimal32 = mystl_type_array<int(sizeof(float) >= 4) + int(sizeof(double) >= 4) + int(sizeof(long double) >= 4) - 1, long double, double, float>::type;
	using mystl__Decimal64 = mystl_type_array<int(sizeof(float) >= 8) + int(sizeof(double) >= 8) + int(sizeof(long double) >= 8) - 1, long double, double, float>::type;
	using mystl__Decimal128 = mystl_type_array<int(sizeof(float) >= 16) + int(sizeof(double) >= 16) + int(sizeof(long double) >= 16) - 1, long double, double, float>::type;
#endif
	constexpr bool canuse_fabsd32 = !mystl_is_equal<mystl__Decimal32, mystl_error_type>::val;
	constexpr bool canuse_fabsd64 = !mystl_is_equal<mystl__Decimal64, mystl_error_type>::val;
	constexpr bool canuse_fabsd128 = !mystl_is_equal<mystl__Decimal128, mystl_error_type>::val;

	mystl__Decimal32 fabsd32(mystl__Decimal32 x) { return x < 0 ? -x : x; }
	mystl__Decimal64 fabsd64(mystl__Decimal64 x) { return x < 0 ? -x : x; }
	mystl__Decimal128 fabsd128(mystl__Decimal128 x) { return x < 0 ? -x : x; }

fmod 系列 & floor 系列

显然,a mod b=a−b×⌊ab⌋a \bmod b = a - b \times \left \lfloor \dfrac{a}{b} \right \rfloor。

所以我们尝试先实现 floor 系列函数。

然而这个小 β\beta 并不会,于是在学术版发了个帖,遇见了两位大神 @litjohn 和 @Terrible。

然而 @Terrible 大神的代码实力太过强劲,我看不懂,贴在这里,有没有大神解释一下(glibc 的 floor 函数实现):

C++
/* Round double to integer away from zero.
   Copyright (C) 2011-2024 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */

/* Based on a version which carries the following copyright:  */

/*
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunPro, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

#define NO_MATH_REDIRECT
#include <math.h>
#include <math_private.h>
#include <stdint.h>
#include <libm-alias-double.h>
#include <math-use-builtins.h>

/*
 * floor(x)
 * Return x rounded toward -inf to integral value
 * Method:
 *	Bit twiddling.
 */


double
__floor (double x)
{
#if USE_FLOOR_BUILTIN
  return __builtin_floor (x);
#else
  /* Use generic implementation.  */
  int64_t i0;
  EXTRACT_WORDS64 (i0, x);
  int32_t j0 = ((i0 >> 52) & 0x7ff) - 0x3ff;
  if (__glibc_likely (j0 < 52))
    {
      if (j0 < 0)
	{
	  /* return 0 * sign (x) if |x| < 1  */
	  if (i0 >= 0)
	    i0 = 0;
	  else if ((i0 & 0x7fffffffffffffffl) != 0)
	    i0 = 0xbff0000000000000l;
	}
      else
	{
	  uint64_t i = 0x000fffffffffffffl >> j0;
	  if ((i0 & i) == 0)
	    return x;			 /* x is integral */
	  if (i0 < 0)
	    i0 += 0x0010000000000000l >> j0;
	  i0 &= ~i;
	}
      INSERT_WORDS64 (x, i0);
    }
  else if (j0 == 0x400)
    return x + x;			/* inf or NaN */
  return x;
#endif /* ! USE_FLOOR_BUILTIN  */
}
#ifndef __floor
libm_alias_double (__floor, floor)
#endif
// 小 β 注:INSERT_WORDS64(x,y) 相当于 *(long long *)&x = *(long long *)&y,也就是把 y 中的数据逐字节复制进 x 中。EXTRACT_WORDS64 类似。

于是我们使用 @litjohn 的思路。

这位神仙敏锐地指出,虽然浮点类型能够表示极大的数字,但是如果太大

原文