randomness icon indicating copy to clipboard operation
randomness copied to clipboard

我需要帮助,GM/T 0005-2021 使用编程语言c++ 2020标准重写时遇到问题。

Open Twilight-Dream-Of-Magic opened this issue 3 years ago • 4 comments

求求该仓库的主人帮忙看一看,我算法哪里写错了。 @emmansun

// Alpha 显著性水平α
		constexpr double Alpha = 0.01;

		// AlphaT 分布均匀性的显著性水平
		constexpr double AlphaT = 0.0001;

		//TestResult 检测结果
		struct TestResult
		{
			std::string Name; //用于测试的统计算法名称
			double P; // 检测结果P_value1
			double Q; // 检测结果Q_value1
			double P2; // 检测结果P_value2
			double Q2; // 检测结果Q_value2
			bool RandomnessPass = false; // 是否大于等于显著水平
			bool RandomnessPass2 = false; // 是否大于等于显著水平

			TestResult()
				:
				Name(""), P(0.0), Q(0.0), P2(0.0), Q2(0.0), RandomnessPass(false)
			{
				
			}

			TestResult(std::string name, double p, double q, bool pass)
				:
				Name(name), P(p), Q(q), P2(0.0), Q2(0.0), RandomnessPass(pass)
			{
				
			}

			//For OverlappingTest
			TestResult(std::string name, double p, double p2, double q, double q2, bool randomness_pass)
				:
				Name(name), P(p), P2(p2), Q(q), Q2(q2), RandomnessPass(randomness_pass)
			{
				
			}

			//For CumulativeSumsTest
			TestResult(std::string name, double p, double p2, double q, double q2, bool randomness_pass, bool randomness_pass2)
				:
				Name(name), P(p), P2(p2), Q(q), Q2(q2), RandomnessPass(randomness_pass), RandomnessPass2(randomness_pass2)
			{
				
			}
		};

CumulativeSumsTest.hpp

namespace ChineseCryptographicStandard::RandomnessTestingSpecification
{
	class CumulativeSumsTest
	{
	private:

		double compute_p_value(int bits_size, int max_excursion)
		{
			double SumA = 0.0;
			double SumB = 0.0;
			int StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) + 1.0) / 4.0)));
			int EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));

			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) - 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumA = SumA + LeftValue - RightValue;
			}

			StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) - 3.0) / 4.0)));
			EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));
			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 3.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumB = SumB + LeftValue - RightValue;
			}

			return 1.0 - SumA + SumB;
		}

		std::tuple<double, double, double, double> TestFunction( const std::vector<bool>& bits )
		{
			int n = bits.size();

			if ( n == 0 )
			{
				throw std::runtime_error( "please provide test bits" );
			}

			std::vector<int> bits_copy(bits.size(), 0);
			
			//Convert all the zeros in the array to -1
			for ( size_t i = 0; i < bits.size(); ++i )
			{
				bits_copy[ i ] = bits[ i ] == 0 ? -1 : 1;
			}

			//Convert all the zeros in the array to -1
			int ForwardSum = 0;
			int BackwardSum = 0;
			int ForwardSumMax = 0;
			int BackwardSumMax = 0;
			for( auto i = 0; i < bits_copy.size(); i++ )
			{
				ForwardSum += bits_copy[i];
				BackwardSum += bits_copy[bits_copy.size() - 1 -i];
				ForwardSumMax = std::max(::abs(ForwardSum), ForwardSumMax);
				BackwardSumMax = std::max(::abs(BackwardSum), BackwardSumMax);
			}

			//Compute the P-Value
			double ForwardP = this->compute_p_value(bits_copy.size(), ForwardSumMax);
			double BackwardP = this->compute_p_value(bits_copy.size(), BackwardSumMax);

			std::make_tuple(ForwardP, ForwardP, BackwardP, BackwardP);
		}

	public:
		// CumulativeSumsTest 累加和检测
		TestResult Run( const std::vector<bool>& bits )
		{
			auto [ p, q, p2, q2 ] = TestFunction( bits );
			return TestResult( "CumulativeSumsTest", p, p2, q, q2, p >= Alpha, p2 >= Alpha );  // Assuming Alpha is a predefined constant
		}
	};
}
CumulativeSumsTest CumulativeSumsTestObject;
		Result = CumulativeSumsTestObject.Run(MathAndUtils::Byte2BitArray({0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x08}));
		P_ValueString = GenerateResultString(Result.P);
		if( P_ValueString != std::string("0.219194") )
		{
			std::cout << "CumulativeSumsTest (Forward) Function implementation is not sanity !!!!" << std::endl;
			std::cout << "P-Value:" << P_ValueString << std::endl;
			std::cout << "Q-Value:" << Q_ValueString << std::endl;
		}
		else
		{
			std::cout << "CumulativeSumsTest (Forward) Function implementation is sanity." << std::endl;
		}
		Q_ValueString = GenerateResultString(Result.Q);
		if( Q_ValueString != std::string("0.114866") )
		{
			std::cout << "CumulativeSumsTest (Backward) Function implementation is not sanity !!!!" << std::endl;
			std::cout << "P-Value:" << P_ValueString << std::endl;
			std::cout << "Q-Value:" << Q_ValueString << std::endl;
		}
		else
		{
			std::cout << "CumulativeSumsTest (Backward) Function implementation is sanity." << std::endl;
		}
CumulativeSumsTest (Forward) Function implementation is not sanity !!!!
P-Value:0.000000
Q-Value:0.307543
CumulativeSumsTest (Backward) Function implementation is not sanity !!!!
P-Value:0.000000
Q-Value:0.000000

ApproximateEntropyProtoTest.hpp

namespace ChineseCryptographicStandard::RandomnessTestingSpecification
{
	class ApproximateEntropyProtoTest
	{
	private:
		int pattern_to_int( std::vector<bool>::const_iterator begin, std::vector<bool>::const_iterator end )
		{
			int result = 0;
			for ( auto it = begin; it != end; ++it )
			{
				result = ( result << 1 ) + *it;
			}
			return result;
		}

		std::pair<double, double> TestFunction( const std::vector<bool>& bits, int block_length )
		{
			int n = bits.size();
			if ( n == 0 )
			{
				throw std::invalid_argument( "please provide test bits" );
			}

			std::vector<double> phi_m;
			for ( int iteration = block_length; iteration < block_length + 2; ++iteration )
			{
				std::vector<bool> padded_bits( bits );
				padded_bits.insert( padded_bits.end(), bits.begin(), bits.begin() + iteration - 1 );

				std::vector<int> counts( 1 << iteration, 0 );
				for ( int i = 0; i < ( 1 << iteration ); ++i )
				{
					int count = 0;
					for ( size_t j = 0; j < bits.size(); ++j )
					{
						if ( pattern_to_int( padded_bits.begin() + j, padded_bits.begin() + j + iteration ) == i )
						{
							count++;
						}
					}
					counts[ i ] = count;
				}

				std::vector<double> c_i( counts.size() );
				for ( size_t i = 0; i < counts.size(); ++i )
				{
					c_i[ i ] = static_cast<double>( counts[ i ] ) / bits.size();
				}

				double sum = 0.0;
				for ( const auto& val : c_i )
				{
					if ( val > 0.0 )
					{
						sum += val * std::log10( val / 10.0 );
					}
				}
				phi_m.push_back( sum );
			}

			double chi_square = 2 * bits.size() * ( std::log( 2 ) - ( phi_m[ 0 ] - phi_m[ 1 ] ) );
			double p_value = MathAndUtils::incomplete_gamma_q( 1 << ( block_length - 1 ), chi_square / 2.0 );
			return std::make_pair( p_value, p_value );
		}

	public:
		// ApproximateEntropyProto 近似熵检测
		// bits: 待检测序列
		// m: m长度
		TestResult Run( const std::vector<bool>& bits, int m = 5 )
		{
			auto [ p, q ] = this->TestFunction( bits, m );
			return TestResult( "ApproximateEntropyProtoTest", p, q, p >= Alpha );
		}
	};
}
ApproximateEntropyProtoTest ApproximateEntropyProtoTestObject;
		Result = ApproximateEntropyProtoTestObject.Run(MathAndUtils::Byte2BitArray({0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80}), 2);
		P_ValueString = GenerateResultString(Result.P);
		Q_ValueString = GenerateResultString(Result.Q);
		if( P_ValueString != std::string("0.235301") || Q_ValueString != std::string("0.235301") )
		{
			std::cout << "ApproximateEntropyProtoTest Function implementation is not sanity !!!!" << std::endl;
			std::cout << "P-Value:" << P_ValueString << std::endl;
			std::cout << "Q-Value:" << Q_ValueString << std::endl;
		}
		else
		{
			std::cout << "ApproximateEntropyProtoTest Function implementation is sanity." << std::endl;
		}
ApproximateEntropyProtoTest Function implementation is not sanity !!!!
P-Value:0.000000
Q-Value:0.000000

DiscreteFourierTransformTest.hpp

namespace ChineseCryptographicStandard::RandomnessTestingSpecification
{
	class DiscreteFourierTransformTest
	{
	public:
		TestResult Run( const std::vector<bool>& bits )
		{
			auto [p, q] = this->TestFunction(bits);
			return TestResult("DiscreteFourierTransformTest", p, q, p >= Alpha);
		}

	private:
		std::vector<bool> bits;

		std::pair<double, double> TestFunction( const std::vector<bool>& bits )
		{
			std::vector<int> bits_copy(bits.size());
			for ( size_t i = 0; i < bits.size(); ++i )
			{
				bits_copy[ i ] = bits[ i ] == 0 ? -1 : 1;
			}

			Eigen::VectorXd input( bits_copy.size() );
			for ( int i = 0; i < bits.size(); ++i )
			{
				input( i ) = static_cast<double>( bits_copy[ i ] );
			}

			Eigen::FFT<double> fft;
			Eigen::VectorXcd   output( bits_copy.size() );
			fft.fwd( output, input );

			Eigen::VectorXd magnitudes( bits_copy.size() / 2 );
			for ( int i = 0; i < bits_copy.size() / 2; ++i )
			{
				magnitudes( i ) = std::abs( output( i ) );
			}

			double threshold = ::sqrt( 2.995732274 * bits_copy.size() );
			double expected_peaks = 0.95 * bits_copy.size() / 2.0;
			double counted_peaks = 0;

			for ( int i = 0; i < bits_copy.size() / 2; ++i )
			{
				if ( magnitudes( i ) < threshold )
				{
					counted_peaks++;
				}
			}

			double normalized_difference = ( counted_peaks - expected_peaks ) / ::sqrt( ( bits_copy.size() / 3.8 ) * 0.95 * 0.05 );
			double p_value = MathAndUtils::erfc( ::abs( normalized_difference ) / ::sqrt( 2 ) );
			double q_value = MathAndUtils::erfc( normalized_difference / ::sqrt( 2 ) ) / 2.0;

			return std::make_pair(p_value, q_value);
		}
	};
}
DiscreteFourierTransformTest DiscreteFourierTransformTestObject;
		Result = DiscreteFourierTransformTestObject.Run(MathAndUtils::Byte2BitArray({0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x08}));
		P_ValueString = GenerateResultString(Result.P);
		Q_ValueString = GenerateResultString(Result.Q);
		if( P_ValueString != std::string("0.654721") || Q_ValueString != std::string("0.327360") )
		{
			std::cout << "DiscreteFourierTransformTest Function implementation is not sanity !!!!" << std::endl;
			std::cout << "P-Value:" << P_ValueString << std::endl;
			std::cout << "Q-Value:" << Q_ValueString << std::endl;
		}
		else
		{
			std::cout << "DiscreteFourierTransformTest Function implementation is sanity." << std::endl;
		}
DiscreteFourierTransformTest Function implementation is not sanity !!!!
P-Value:0.035297
Q-Value:0.982352

Twilight-Dream-Of-Magic avatar Apr 09 '23 05:04 Twilight-Dream-Of-Magic

你先小心核对一个算法,譬如:

		double compute_p_value(int bits_size, int max_excursion)
		{
			double SumA = 0.0;
			double SumB = 0.0;
			int StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) + 1.0) / 4.0)));
			int EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));

			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) - 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumA = SumA + LeftValue - RightValue;
			}

			StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) - 3.0) / 4.0)));
			EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));
			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 3.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumB = SumB + LeftValue - RightValue;
			}

			return 1.0 - SumA + SumB;
		}
  1. StartLoop / EndLoop 本来就是整型,没有必要先对bits_size转型,应该都是整型操作;
  2. 请仔细核对算法:double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
  3. https://zh.wikipedia.org/wiki/%E8%AF%AF%E5%B7%AE%E5%87%BD%E6%95%B0

image

emmansun avatar Apr 10 '23 03:04 emmansun

你先小心核对一个算法,譬如:

		double compute_p_value(int bits_size, int max_excursion)
		{
			double SumA = 0.0;
			double SumB = 0.0;
			int StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) + 1.0) / 4.0)));
			int EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));

			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) - 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumA = SumA + LeftValue - RightValue;
			}

			StartLoop = static_cast<int>(::floor((((static_cast<double>(-bits_size) / max_excursion) - 3.0) / 4.0)));
			EndLoop = static_cast<int>(::floor((((static_cast<double>(bits_size) / max_excursion) - 1.0) / 4.0)));
			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 3.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				double RightValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
				++StartLoop;
				SumB = SumB + LeftValue - RightValue;
			}

			return 1.0 - SumA + SumB;
		}
  1. StartLoop / EndLoop 本来就是整型,没有必要先对bits_size转型,应该都是整型操作;
  2. 请仔细核对算法:double LeftValue = 0.5 * MathAndUtils::erfc(-(((4.0 * StartLoop) + 1.0) * max_excursion) / ::sqrt(bits_size) * ::sqrt(0.5));
  3. https://zh.wikipedia.org/wiki/%E8%AF%AF%E5%B7%AE%E5%87%BD%E6%95%B0

image

//https://en.wikipedia.org/wiki/Error_function
		//Cumulative distribution function
		//标准正态累积分布函数
		double phi(double x)
		{
			return 0.5 * MathAndUtils::erfc( -(x / ::sqrt(2)) );
		}

		double compute_p_value(int bits_size, int max_excursion)
		{
			double SumA = 0.0;
			double SumB = 0.0;
			int StartLoop = static_cast<int>(::floor(((( (-bits_size) / max_excursion) + 1.0) / 4.0)));
			int EndLoop = static_cast<int>(::floor(((( (bits_size) / max_excursion) - 1.0) / 4.0)));

			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = this->phi( (((4.0 * StartLoop) + 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				double RightValue = this->phi( (((4.0 * StartLoop) - 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				++StartLoop;
				SumA = SumA + (LeftValue - RightValue);
			}

			StartLoop = static_cast<int>(::floor(((( (-bits_size) / max_excursion) - 3.0) / 4.0)));
			EndLoop = static_cast<int>(::floor(((( (bits_size) / max_excursion) - 1.0) / 4.0)));
			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = this->phi( (((4.0 * StartLoop) + 3.0 ) * max_excursion) / ::sqrt(bits_size) );
				double RightValue = this->phi( (((4.0 * StartLoop) + 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				++StartLoop;
				SumB = SumB + (LeftValue - RightValue);
			}

			return 1.0 - (SumA + SumB);
		}

是这样?

Twilight-Dream-Of-Magic avatar Apr 10 '23 08:04 Twilight-Dream-Of-Magic

你没有erf(x)实现,有erfc(x)也能按下面的两个等式推导出来啊。1 - 0.5 * MathAndUtils::erfc( x / ::sqrt(2) ); image

emmansun avatar Apr 10 '23 09:04 emmansun

//https://en.wikipedia.org/wiki/Error_function
		//Cumulative distribution function
		//标准正态累积分布函数
		double phi(double x)
		{
			//return 1 - 0.5 * ::erfc( x / ::sqrt(2) );
                        return 0.5 + 0.5 * ::erf(x / ::sqrt(2.0));
		}

		double compute_p_value(int bits_size, int max_excursion)
		{
			double SumA = 0.0;
			double SumB = 0.0;
			int StartLoop = static_cast<int>(::floor(((( (-bits_size) / max_excursion) + 1.0) / 4.0)));
			int EndLoop = static_cast<int>(::floor(((( (bits_size) / max_excursion) - 1.0) / 4.0)));

			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = this->phi( (((4.0 * StartLoop) + 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				double RightValue = this->phi( (((4.0 * StartLoop) - 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				++StartLoop;
				SumA = SumA + (LeftValue - RightValue);
			}

			StartLoop = static_cast<int>(::floor(((( (-bits_size) / max_excursion) - 3.0) / 4.0)));
			EndLoop = static_cast<int>(::floor(((( (bits_size) / max_excursion) - 1.0) / 4.0)));
			while( StartLoop < EndLoop + 1 )
			{
				double LeftValue = this->phi( (((4.0 * StartLoop) + 3.0 ) * max_excursion) / ::sqrt(bits_size) );
				double RightValue = this->phi( (((4.0 * StartLoop) + 1.0 ) * max_excursion) / ::sqrt(bits_size) );
				++StartLoop;
				SumB = SumB + (LeftValue - RightValue);
			}

			return 1.0 - (SumA + SumB);
		}
CumulativeSumsTest (Forward) Function implementation is not sanity !!!!
P-Value:0.000000
Q-Value:0.307543
CumulativeSumsTest (Backward) Function implementation is not sanity !!!!
P-Value:0.000000
Q-Value:0.000000

我到底哪儿错了呀?怎么弄都是这个结果呀。

Twilight-Dream-Of-Magic avatar Apr 10 '23 12:04 Twilight-Dream-Of-Magic