мы с моим лучшем другом поспорили на бутылку пива,...

تم الإنشاء في: ٢٢ أغسطس ٢٠٢٥

تمت الإجابة باستخدام GPT-5 Thinking بواسطة Chat01

سؤال

мы с моим лучшем другом поспорили на бутылку пива, он хвастался тем какой код написал для своей научной работы а я ничего не понимаю в программировании и тогда я сказал что если он скинет мне свой код и ИИ действительно скажет что он крутой программист то я должен ему банку пива иначе он мне, вот код: #pragma once

#include "pch.h"

#pragma strict_gs_check(push, off)
#pragma optimize(on)
#pragma inline_recursion(on)
#pragma inline_depth(255u)
#pragma runtime_checks("", off)
#pragma check_stack(off)
#pragma fenv_access(off)
#pragma auto_inline(on)
#pragma managed(push, off)

static __declspec(noalias) __forceinline float xor_rand_grsh(
uint32_t& __restrict state) noexcept
{
uint32_t s = state;
s ^= s << 13u;
s ^= s >> 17u;
s ^= s << 5u;
state = s;
return fmaf(s, 0x1.0p-31f, -1.0f);
}

static __declspec(noalias) __forceinline float xor_rand(
uint32_t& __restrict state) noexcept
{
uint32_t s = state;
s ^= s << 13u;
s ^= s >> 17u;
s ^= s << 5u;
state = s;
return s * 0x1.0p-32f;
}

static __declspec(noalias) __forceinline float HillFunc(
const float x, uint32_t seed) noexcept
{
uint32_t i = 0u;
alignas(64u) float angles[14u];
const float start_angle = 6.28318530717958647692f * x;

#pragma loop(ivdep)
while (i < 14u) {
angles[i] = start_angle * (i + 1u);
++i;
}

text
alignas(64u) float sin_vals[14u]; alignas(64u) float cos_vals[14u]; fabe13_sincos_scalar_simple(angles, sin_vals, cos_vals, 14u); float res = fmaf(xor_rand(seed), 2.0f, -1.1f); --i; while (i >= 0u) { res += fmaf(fmaf(xor_rand(seed), 2.0f, -1.1f), sin_vals[i], fmaf(xor_rand(seed), 2.0f, -1.1f) * cos_vals[i]); --i; } return res;

}

static __declspec(noalias) __forceinline float ShekelFunc(
const float x, uint32_t seed) noexcept
{
uint32_t i = 0u;
float res = 0.0f;

text
while (i < 10u) { const float r = xor_rand(seed); const float x_part = fmaf(-r, 10.0f, x); res -= 1.0f / fmaf(fmaf(xor_rand(seed), 20.0f, 0.5f), x_part * x_part, fmaf(xor_rand(seed), 0.4f, 1.0f)); ++i; } return res;

}

static __declspec(noalias) __forceinline float GrishaginFunc(
const float x1, const float x2, uint32_t seed) noexcept
{
uint32_t i = 0u;
alignas(64u) float angles_i[8u];
alignas(64u) float angles_j[8u];

#pragma loop(ivdep)
while (i < 8u) {
const float pi_mult = 3.14159265358979323846f * (i + 1u);
angles_i[i] = pi_mult * x1;
angles_j[i] = pi_mult * x2;
++i;
}

text
alignas(64u) float sin_i[8u], cos_i[8u]; alignas(64u) float sin_j[8u], cos_j[8u]; fabe13_sincos_scalar_simple(angles_i, sin_i, cos_i, 8u); fabe13_sincos_scalar_simple(angles_j, sin_j, cos_j, 8u); --i; float part1 = 0.0f; float part2 = 0.0f; while (i >= 0u) { uint32_t j = 0u; while (j < 8u) { const float sin_term = sin_i[i] * sin_i[i]; const float cos_term = cos_j[j] * cos_j[j]; part1 = fmaf(xor_rand_grsh(seed), sin_term, fmaf(xor_rand_grsh(seed), cos_term, part1)); part2 = fmaf(-xor_rand_grsh(seed), cos_term, fmaf(xor_rand_grsh(seed), sin_term, part2)); ++j; } --i; } return -sqrtf(fmaf(part1, part1, part2 * part2));

}

static __declspec(noalias) __forceinline float RastriginFunc(
const float x1,
const float x2) noexcept
{
const float term1 = fmaf(x1, x1, x2 * x2);
return (term1 - fmaf(
fabe13_cos(6.28318530717958647692f * x1) +
fabe13_cos(6.28318530717958647692f * x2),
10.0f,
-14.6f)) *
fmaf(-term1, 0.25f, 18.42f);
}

static __declspec(noalias) __forceinline float Shag(
const float _m,
const float x1,
const float x2,
const float y1,
const float y2,
const uint32_t _N,
const float _r) noexcept
{
const float diff = y2 - y1;
return _N == 1u
? fmaf(-(1.0f / _m), diff, x1 + x2) * 0.5f
: diff > 0u
? fmaf(-(1.0f / (_m * _m)), (diff) * (diff)_r, x1 + x2) * 0.5f
: fmaf(1.0f / (_m * _m), (diff) * (diff)
_r, x1 + x2) * 0.5f;
}

#pragma pack(push, 1u)
struct Interval final
{
public:
std::pair<float, float> start;
std::pair<float, float> end;
float M;
float R;

text
__declspec(noalias) __forceinline Interval( const std::pair<float, float>& __restrict _start, const std::pair<float, float>& __restrict _end, const uint32_t _N) noexcept : start(_start) , end(_end) , M(_N == 1u ? fabsf(_end.second - _start.second) / (_end.first - _start.first) : _N == 2u ? fabsf(_end.second - _start.second) / sqrtf(_end.first - _start.first) : fabsf(_end.second - _start.second) / powf(_end.first - _start.first, 1.0f / float(_N))) { } __declspec(noalias) __forceinline void ChangeCharacteristic( const float _m, const uint32_t _N) noexcept { const float delta_x = end.first - start.first; const float delta_y = end.second - start.second; switch (_N) { case 1u: R = fmaf( -(end.second + start.second), 2.0f, fmaf(_m, delta_x, (delta_y * delta_y) / (_m * delta_x))); break; case 2u: { const float sqrt_dx = sqrtf(delta_x); R = fmaf( -(end.second + start.second), 2.0f, fmaf(_m, sqrt_dx, (delta_y * delta_y) / (_m * sqrt_dx))); } break; default: { const float pow_dx = powf(delta_x, 1.0f / _N); R = fmaf( -(end.second + start.second), 2.0f, fmaf(_m, pow_dx, (delta_y * delta_y) / (_m * pow_dx))); } break; } }

};
#pragma pack(pop)

__declspec(noalias) __forceinline static bool Compare(
const Interval& __restrict a,
const Interval& __restrict b) noexcept
{
return a.R < b.R;
}

#pragma pack(push, 1u)
enum List : uint8_t {
Top = 0b00,
Down = 0b01,
Left = 0b10,
Right = 0b11
};
#pragma pack(pop)

#pragma pack(push, 1u)
struct PeanoCurve_2D final
{
public:
List Type;
uint32_t razvertka;
float a, b, c, d, x1, x2;
PeanoCurve_2D* __restrict DownLeft;
PeanoCurve_2D* __restrict TopLeft;
PeanoCurve_2D* __restrict TopRight;
PeanoCurve_2D* __restrict DownRight;

text
__declspec(noalias) __forceinline PeanoCurve_2D( const List _Type, uint32_t _razvertka, const float _a, const float _b, const float _c, const float _d) noexcept : Type(_Type), razvertka(_razvertka), a(_a), b(_b), c(_c), d(_d), x1(fmaf(0.5f, _a, 0.5f * _b)), x2(fmaf(0.5f, _c, 0.5f * _d)) { if (_razvertka-- != 0u) { if (_razvertka > 4u) { switch (_Type) { case Top: tbb::parallel_invoke( [&]() { DownLeft = new PeanoCurve_2D(Right, _razvertka, _a, x1, _c, x2); }, [&]() { TopLeft = new PeanoCurve_2D(Top, _razvertka, _a, x1, x2, _d); }, [&]() { TopRight = new PeanoCurve_2D(Top, _razvertka, x1, _b, x2, _d); }, [&]() { DownRight = new PeanoCurve_2D(Left, _razvertka, x1, _b, _c, x2); } ); break; case Down: tbb::parallel_invoke( [&]() { TopRight = new PeanoCurve_2D(Left, _razvertka, x1, _b, x2, _d); }, [&]() { DownRight = new PeanoCurve_2D(Down, _razvertka, x1, _b, _c, x2); }, [&]() { DownLeft = new PeanoCurve_2D(Down, _razvertka, _a, x1, _c, x2); }, [&]() { TopLeft = new PeanoCurve_2D(Right, _razvertka, _a, x1, x2, _d); } ); break; case Right: tbb::parallel_invoke( [&]() { DownLeft = new PeanoCurve_2D(Top, _razvertka, _a, x1, _c, x2); }, [&]() { DownRight = new PeanoCurve_2D(Right, _razvertka, x1, _b, _c, x2); }, [&]() { TopRight = new PeanoCurve_2D(Right, _razvertka, x1, _b, x2, _d); }, [&]() { TopLeft = new PeanoCurve_2D(Down, _razvertka, _a, x1, x2, _d); } ); break; case Left: tbb::parallel_invoke( [&]() { TopRight = new PeanoCurve_2D(Down, _razvertka, x1, _b, x2, _d); }, [&]() { TopLeft = new PeanoCurve_2D(Left, _razvertka, _a, x1, x2, _d); }, [&]() { DownLeft = new PeanoCurve_2D(Left, _razvertka, _a, x1, _c, x2); }, [&]() { DownRight = new PeanoCurve_2D(Top, _razvertka, x1, _b, _c, x2); } ); break; } } else { switch (_Type) { case Top: DownLeft = new PeanoCurve_2D(Right, _razvertka, _a, x1, _c, x2); TopLeft = new PeanoCurve_2D(Top, _razvertka, _a, x1, x2, _d); TopRight = new PeanoCurve_2D(Top, _razvertka, x1, _b, x2, _d); DownRight = new PeanoCurve_2D(Left, _razvertka, x1, _b, _c, x2); break; case Down: TopRight = new PeanoCurve_2D(Left, _razvertka, x1, _b, x2, _d); DownRight = new PeanoCurve_2D(Down, _razvertka, x1, _b, _c, x2); DownLeft = new PeanoCurve_2D(Down, _razvertka, _a, x1, _c, x2); TopLeft = new PeanoCurve_2D(Right, _razvertka, _a, x1, x2, _d); break; case Right: DownLeft = new PeanoCurve_2D(Top, _razvertka, _a, x1, _c, x2); DownRight = new PeanoCurve_2D(Right, _razvertka, x1, _b, _c, x2); TopRight = new PeanoCurve_2D(Right, _razvertka, x1, _b, x2, _d); TopLeft = new PeanoCurve_2D(Down, _razvertka, _a, x1, x2, _d); break; case Left: TopRight = new PeanoCurve_2D(Down, _razvertka, x1, _b, x2, _d); TopLeft = new PeanoCurve_2D(Left, _razvertka, _a, x1, x2, _d); DownLeft = new PeanoCurve_2D(Left, _razvertka, _a, x1, _c, x2); DownRight = new PeanoCurve_2D(Top, _razvertka, x1, _b, _c, x2); break; } } } } __declspec(noalias) __forceinline PeanoCurve_2D* HitTest_2D(float x) noexcept { uint32_t i = 0u; const uint32_t _razvertka = this->razvertka; uint32_t num; const float this_a = this->a; x -= this_a; const float b_minus_a = this->b - this_a; const float inv_b_minus_a = 1.0f / b_minus_a; PeanoCurve_2D* Curr = this; while (i != _razvertka) { const uint32_t shift = 1u << ++i + i; num = shift * x * inv_b_minus_a; x = fmaf(-(1.0f / shift) * num, b_minus_a, x); const List currType = Curr->Type; switch (num) { case 0u: Curr = (currType == Top || currType == Right) ? Curr->DownLeft : Curr->TopRight; break; case 1u: Curr = (currType == Top || currType == Left) ? Curr->TopLeft : Curr->DownRight; break; case 2u: Curr = (currType == Top || currType == Right) ? Curr->TopRight : Curr->DownLeft; break; case 3u: Curr = (currType == Top || currType == Left) ? Curr->DownRight : Curr->TopLeft; break; } } return Curr; } __declspec(noalias) __forceinline float FindX_2D(float target_x1, float target_x2) noexcept { uint32_t _razvertka = this->razvertka; uint32_t _razvertka1 = _razvertka; float x1, x2, x = this->a; const float b_minus_a = this->b - x; PeanoCurve_2D* Curr = this; while (_razvertka != 0u) { const int32_t exponent = _razvertka-- - _razvertka1 << 1u; x1 = Curr->x1; x2 = Curr->x2; const List currType = Curr->Type; if (target_x1 > x1 && target_x2 > x2) { Curr = Curr->TopRight; if (currType == Top || currType == Right) { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.5f, b_minus_a, x); } } else if (target_x1 < x1 && target_x2 > x2) { Curr = Curr->TopLeft; if (currType == Top || currType == Left) { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.25f, b_minus_a, x); } else { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.75f, b_minus_a, x); } } else if (target_x1 < x1 && target_x2 < x2) { Curr = Curr->DownLeft; if (currType == Down || currType == Left) { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.5f, b_minus_a, x); } } else { Curr = Curr->DownRight; if (currType == Top || currType == Left) { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.75f, b_minus_a, x); } else { x = fmaf((exponent > 0u ? 1u << exponent : 1.0f / (1u << -exponent)) * 0.25f, b_minus_a, x); } } } return x; }

};
#pragma pack(pop)

__declspec(dllexport) __declspec(noalias)std::vector<float> Base_LNA_1_2_Mer_AGP(
const uint32_t N, const uint32_t global_iterations, const float a,
const float b, const float c, const float d, const uint32_t r,
const bool mode, const float epsilon, const uint32_t seed) noexcept
{
if (N == 1u) {
const float initial_length = b - a;
float dmax = initial_length;

text
std::vector<float> Extr; Extr.reserve((global_iterations << 1u) + 2u); std::vector<Interval> R; R.reserve(global_iterations + 1u); float best_f = ShekelFunc(a, seed); const float end_val = ShekelFunc(b, seed); uint32_t schetchick = 0u; std::pair<float, float> x_Rmax = std::make_pair(a, b); std::pair<float, float> y_Rmax = std::make_pair(best_f, end_val); R.emplace_back(std::make_pair(a, best_f), std::make_pair(b, end_val), N); float Mmax = R.front().M; float m = r * Mmax; while (true) { if (++schetchick == global_iterations) { const Interval& front = R.front(); Extr.emplace_back(front.end.first - front.start.first); Extr.emplace_back(global_iterations); return Extr; } const float x1 = x_Rmax.first; const float x2 = x_Rmax.second; const float y1 = y_Rmax.first; const float y2 = y_Rmax.second; const float new_point = Shag(m, x1, x2, y1, y2, N, r); const float new_value = ShekelFunc(new_point, seed); std::pair<float, float> promejutochnaya_tochka = std::make_pair(new_point, new_value); if (new_value < best_f) { best_f = new_value; Extr.emplace_back(best_f); Extr.emplace_back(new_point); } std::pop_heap(R.begin(), R.end(), Compare); Interval promejutochny_otrezok = std::move(R.back()); R.pop_back(); Interval curr(promejutochny_otrezok.start, promejutochnaya_tochka, N); Interval curr1(promejutochnaya_tochka, promejutochny_otrezok.end, N); const float currM = curr.M > curr1.M ? curr.M : curr1.M; const float len2 = promejutochny_otrezok.end.first - new_point; const float len1 = new_point - promejutochny_otrezok.start.first; const size_t r_size = R.size(); if (len2 + len1 == dmax) { dmax = len2 > len1 ? len2 : len1;

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float len = R[i].end.first - R[i].start.first;
if (len > dmax) {
dmax = len;
}
}
}

text
if (mode) { const float threshold_03 = 0.3f * initial_length; if ((threshold_03 > dmax && schetchick % 3u == 0u) || (10.0f * dmax < initial_length)) { if (currM > Mmax) { Mmax = currM; m = r * Mmax; } const float inv_threshold_03 = 1.0f / threshold_03; const float progress = fmaf(-inv_threshold_03, dmax, 1.0f); const float alpha = fmaf(progress, progress, 1.0f); const float betta = 2.0f - alpha; const float inv_dmax = 1.0f / dmax; const float MULTIPLIER = inv_dmax * Mmax; const float global_coeff = fmaf(MULTIPLIER, r, -MULTIPLIER); const float GLOBAL_FACTOR = betta * global_coeff; curr.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len1, curr.M * alpha), N); curr1.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len2, curr1.M * alpha), N);

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float len_item = R[i].end.first - R[i].start.first;
R[i].ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len_item, R[i].M * alpha), N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
if (currM > Mmax) {
Mmax = currM;
m = r * Mmax;
curr.ChangeCharacteristic(m, N);
curr1.ChangeCharacteristic(m, N);
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R[i].ChangeCharacteristic(m, N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
curr.ChangeCharacteristic(m, N);
curr1.ChangeCharacteristic(m, N);
}
}
}
else {
if (currM > Mmax) {
Mmax = currM;
m = r * Mmax;
curr.ChangeCharacteristic(m, N);
curr1.ChangeCharacteristic(m, N);
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R[i].ChangeCharacteristic(m, N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
curr.ChangeCharacteristic(m, N);
curr1.ChangeCharacteristic(m, N);
}
}

text
R.emplace_back(std::move(curr)); std::push_heap(R.begin(), R.end(), Compare); R.emplace_back(std::move(curr1)); std::push_heap(R.begin(), R.end(), Compare); const Interval& top = R.front(); const float interval_length = top.end.first - top.start.first; if (interval_length < epsilon) { Extr.emplace_back(interval_length); Extr.emplace_back(schetchick); return Extr; } x_Rmax = std::make_pair(top.start.first, top.end.first); y_Rmax = std::make_pair(top.start.second, top.end.second); } } else { std::vector<float> Extr; Extr.reserve(3u * global_iterations + 2u); std::vector<Interval> R; R.reserve(global_iterations + 1u); std::vector<Interval> R_Inverted; R_Inverted.reserve(global_iterations + 1u); PeanoCurve_2D Curve = PeanoCurve_2D(Top, 12, a, b, c, d); PeanoCurve_2D Curve_Inverted = PeanoCurve_2D(Down, 12, a, b, c, d); const float divider = 1u << (2u * Curve_Inverted.razvertka + 1u); const float x_addition = (b - a) / divider; const float y_addition = (d - c) / divider; const float true_start = a + x_addition; const float true_end = b - x_addition; const float initial_length = true_end - true_start; float dmax = initial_length; float dmax_Inverted = initial_length; uint32_t schetchick = 0u; std::pair<float, float> start = std::make_pair(true_start, RastriginFunc(true_start, c + y_addition)); std::pair<float, float> end = std::make_pair(true_end, RastriginFunc(true_end, c + y_addition)); std::pair<float, float> start_Inverted = std::make_pair(true_start, RastriginFunc(true_end, d - y_addition)); std::pair<float, float> end_Inverted = std::make_pair(true_end, RastriginFunc(true_start, d - y_addition)); std::pair<float, float> x_Rmax = std::make_pair(start.first, end.first); std::pair<float, float> y_Rmax = std::make_pair(start.second, end.second); std::pair<float, float> x_Rmax_Inverted = std::make_pair(start_Inverted.first, end_Inverted.first); std::pair<float, float> y_Rmax_Inverted = std::make_pair(start_Inverted.second, end_Inverted.second); float best_f = end_Inverted.second; Interval initial_interval(start, end, N); Interval initial_interval_Inverted(start_Inverted, end_Inverted, N); float Mmax = initial_interval.M; float Mmax_Inverted = initial_interval_Inverted.M; float m = r * Mmax; float m_Inverted = r * Mmax_Inverted; R.emplace_back(std::move(initial_interval)); R_Inverted.emplace_back(std::move(initial_interval_Inverted)); while (true) { if (++schetchick == global_iterations) { const Interval& topA = R.front(); const Interval& topB = R_Inverted.front(); const float lenA = topA.end.first - topA.start.first; const float lenB = topB.end.first - topB.start.first; const float interval_length = lenA > lenB ? lenA : lenB; Extr.emplace_back(interval_length); Extr.emplace_back(global_iterations); return Extr; } const float x1A = x_Rmax.first; const float x2A = x_Rmax.second; const float y1A = y_Rmax.first; const float y2A = y_Rmax.second; const float x1B = x_Rmax_Inverted.first; const float x2B = x_Rmax_Inverted.second; const float y1B = y_Rmax_Inverted.first; const float y2B = y_Rmax_Inverted.second; const float new_param_A = Shag(m, x1A, x2A, y1A, y2A, N, r); const float new_param_B = Shag(m_Inverted, x1B, x2B, y1B, y2B, N, r); const float cooling = expf(-schetchick / 200.0f); const uint32_t T = fmaf(20.0f, cooling, 10.0f); const float k = fmaf(0.2f, cooling, 0.7f); PeanoCurve_2D* pA = Curve.HitTest_2D(new_param_A); PeanoCurve_2D* pB = Curve_Inverted.HitTest_2D(new_param_B); if (schetchick % T == 0u && schetchick > T && !R.empty() && !R_Inverted.empty()) { const Interval& topA = R.front(); const Interval& topB = R_Inverted.front(); PeanoCurve_2D* p1A = Curve.HitTest_2D(topA.start.first); PeanoCurve_2D* p2A = Curve.HitTest_2D(topA.end.first); PeanoCurve_2D* p1B = Curve_Inverted.HitTest_2D(topB.start.first); PeanoCurve_2D* p2B = Curve_Inverted.HitTest_2D(topB.end.first); const float newParam1_B = Curve.FindX_2D(p1B->x1, p1B->x2); const float newParam2_B = Curve.FindX_2D(p2B->x1, p2B->x2); const float newParam1_A = Curve_Inverted.FindX_2D(p1A->x1, p1A->x2); const float newParam2_A = Curve_Inverted.FindX_2D(p2A->x1, p2A->x2); std::pair<float, float> newStart_A(newParam1_A, topA.start.second); std::pair<float, float> newEnd_A(newParam2_A, topA.end.second); std::pair<float, float> newStart_B(newParam1_B, topB.start.second); std::pair<float, float> newEnd_B(newParam2_B, topB.end.second); Interval injected_A(newStart_A, newEnd_A, N); Interval injected_B(newStart_B, newEnd_B, N); injected_A.R = topA.R * k; injected_B.R = topB.R * k; R.emplace_back(std::move(injected_B)); std::push_heap(R.begin(), R.end(), Compare); R_Inverted.emplace_back(std::move(injected_A)); std::push_heap(R_Inverted.begin(), R_Inverted.end(), Compare); } const float new_x1_A = pA->x1; const float new_x2_A = pA->x2; const float new_x1_B = pB->x1; const float new_x2_B = pB->x2; const float new_value_A = RastriginFunc(new_x1_A, new_x2_A); const float new_value_B = RastriginFunc(new_x1_B, new_x2_B); std::pair<float, float> promejutochnaya_tochka_A = std::make_pair(new_param_A, new_value_A); std::pair<float, float> promejutochnaya_tochka_B = std::make_pair(new_param_B, new_value_B); if (new_value_A < best_f) { best_f = new_value_A; if (new_value_B < best_f) { best_f = new_value_B; Extr.emplace_back(best_f); Extr.emplace_back(new_x1_B); Extr.emplace_back(new_x2_B); } else { Extr.emplace_back(best_f); Extr.emplace_back(new_x1_A); Extr.emplace_back(new_x2_A); } } else if (new_value_B < best_f) { best_f = new_value_B; Extr.emplace_back(best_f); Extr.emplace_back(new_x1_B); Extr.emplace_back(new_x2_B); } std::pop_heap(R.begin(), R.end(), Compare); Interval promejutochny_otrezok_A = std::move(R.back()); R.pop_back(); std::pop_heap(R_Inverted.begin(), R_Inverted.end(), Compare); Interval promejutochny_otrezok_B = std::move(R_Inverted.back()); R_Inverted.pop_back(); Interval curr_A(promejutochny_otrezok_A.start, promejutochnaya_tochka_A, N); Interval curr1_A(promejutochnaya_tochka_A, promejutochny_otrezok_A.end, N); Interval curr_B(promejutochny_otrezok_B.start, promejutochnaya_tochka_B, N); Interval curr1_B(promejutochnaya_tochka_B, promejutochny_otrezok_B.end, N); const float currM_A = curr1_A.M > curr_A.M ? curr1_A.M : curr_A.M; const float currM_B = curr1_B.M > curr_B.M ? curr1_B.M : curr_B.M; const float len2_A = promejutochny_otrezok_A.end.first - new_param_A; const float len1_A = new_param_A - promejutochny_otrezok_A.start.first; const float len2_B = promejutochny_otrezok_B.end.first - new_param_B; const float len1_B = new_param_B - promejutochny_otrezok_B.start.first; const size_t r_size = R.size(); if (len2_A + len1_A == dmax) { dmax = len2_A > len1_A ? len2_A : len1_A;

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float l = R[i].end.first - R[i].start.first;
if (l > dmax) {
dmax = l;
}
}
}
if (len2_B + len1_B == dmax_Inverted) {
dmax_Inverted = len2_B > len1_B ? len2_B : len1_B;
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float l = R_Inverted[i].end.first - R_Inverted[i].start.first;
if (l > dmax_Inverted) {
dmax_Inverted = l;
}
}
}

text
if (mode) { const float threshold_03 = 0.3f * initial_length; if ((threshold_03 > dmax && schetchick % 3u == 0u) || (10.0f * dmax < initial_length)) { if (currM_A > Mmax) { Mmax = currM_A; m = r * Mmax; } const float inv_threshold_03 = 1.0f / threshold_03; const float progress = fmaf(-inv_threshold_03, dmax, 1.0f); const float alpha = fmaf(progress, progress, 1.0f); const float betta = 2.0f - alpha; const float inv_dmax = 1.0f / dmax; const float MULTIPLIER = inv_dmax * Mmax; const float global_coeff = fmaf(MULTIPLIER, r, -MULTIPLIER); const float GLOBAL_FACTOR = betta * global_coeff; curr_A.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len1_A, curr_A.M * alpha), N); curr1_A.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len2_A, curr1_A.M * alpha), N);

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float li = R[i].end.first - R[i].start.first;
R[i].ChangeCharacteristic(fmaf(GLOBAL_FACTOR, li, R[i].M * alpha), N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
if (currM_A > Mmax) {
Mmax = currM_A;
m = r * Mmax;
curr_A.ChangeCharacteristic(m, N);
curr1_A.ChangeCharacteristic(m, N);
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R[i].ChangeCharacteristic(m, N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
curr_A.ChangeCharacteristic(m, N);
curr1_A.ChangeCharacteristic(m, N);
}
}

text
if ((threshold_03 > dmax_Inverted && schetchick % 3u == 0u) || (10.0f * dmax_Inverted < initial_length)) { if (currM_B > Mmax_Inverted) { Mmax_Inverted = currM_B; m_Inverted = r * Mmax_Inverted; } const float inv_threshold_03 = 1.0f / threshold_03; const float progress = fmaf(-inv_threshold_03, dmax_Inverted, 1.0f); const float alpha = fmaf(progress, progress, 1.0f); const float betta = 2.0f - alpha; const float inv_dmax = 1.0f / dmax_Inverted; const float MULTIPLIER = inv_dmax * Mmax_Inverted; const float global_coeff = fmaf(MULTIPLIER, r, -MULTIPLIER); const float GLOBAL_FACTOR = betta * global_coeff; curr_B.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len1_B, curr_B.M * alpha), N); curr1_B.ChangeCharacteristic(fmaf(GLOBAL_FACTOR, len2_B, curr1_B.M * alpha), N);

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
const float li = R_Inverted[i].end.first - R_Inverted[i].start.first;
R_Inverted[i].ChangeCharacteristic(fmaf(GLOBAL_FACTOR, li, R_Inverted[i].M * alpha), N);
}
std::make_heap(R_Inverted.begin(), R_Inverted.end(), Compare);
}
else {
if (currM_B > Mmax_Inverted) {
Mmax_Inverted = currM_B;
m_Inverted = r * Mmax_Inverted;
curr_B.ChangeCharacteristic(m_Inverted, N);
curr1_B.ChangeCharacteristic(m_Inverted, N);
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R_Inverted[i].ChangeCharacteristic(m_Inverted, N);
}
std::make_heap(R_Inverted.begin(), R_Inverted.end(), Compare);
}
else {
curr_B.ChangeCharacteristic(m_Inverted, N);
curr1_B.ChangeCharacteristic(m_Inverted, N);
}
}
}
else {
if (currM_A > Mmax) {
Mmax = currM_A;
m = r * Mmax;
curr_A.ChangeCharacteristic(m, N);
curr1_A.ChangeCharacteristic(m, N);
#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R[i].ChangeCharacteristic(m, N);
}
std::make_heap(R.begin(), R.end(), Compare);
}
else {
curr_A.ChangeCharacteristic(m, N);
curr1_A.ChangeCharacteristic(m, N);
}

text
if (currM_B > Mmax_Inverted) { Mmax_Inverted = currM_B; m_Inverted = r * Mmax_Inverted; curr_B.ChangeCharacteristic(m_Inverted, N); curr1_B.ChangeCharacteristic(m_Inverted, N);

#pragma loop(ivdep)
for (size_t i = 0u; i < r_size; ++i) {
R_Inverted[i].ChangeCharacteristic(m_Inverted, N);
}
std::make_heap(R_Inverted.begin(), R_Inverted.end(), Compare);
}
else {
curr_B.ChangeCharacteristic(m_Inverted, N);
curr1_B.ChangeCharacteristic(m_Inverted, N);
}
}

text
R.emplace_back(std::move(curr_A)); std::push_heap(R.begin(), R.end(), Compare); R.emplace_back(std::move(curr1_A)); std::push_heap(R.begin(), R.end(), Compare); R_Inverted.emplace_back(std::move(curr_B)); std::push_heap(R_Inverted.begin(), R_Inverted.end(), Compare); R_Inverted.emplace_back(std::move(curr1_B)); std::push_heap(R_Inverted.begin(), R_Inverted.end(), Compare); const Interval& topA = R.front(); const Interval& topB = R_Inverted.front(); const float interval_length_A = topA.end.first - topA.start.first; const float interval_length_B = topB.end.first - topB.start.first; const float interval_length = interval_length_A > interval_length_B ? interval_length_A : interval_length_B; if (interval_length < epsilon) { Extr.emplace_back(interval_length); Extr.emplace_back(schetchick); return Extr; } x_Rmax = std::make_pair(topA.start.first, topA.end.first); y_Rmax = std::make_pair(topA.start.second, topA.end.second); x_Rmax_Inverted = std::make_pair(topB.start.first, topB.end.first); y_Rmax_Inverted = std::make_pair(topB.start.second, topB.end.second); } }

}

الفكرة

Evaluating code quality

The user seems to want an assessment of whether the code demonstrates expertise, focusing on the use of advanced C++ features like Windows/MSVC-specific intrinsics, custom function implementation, parallelism, and optimization tests. The focus is on practical, high-level techniques such as parallelism, custom math functions, and optimization methods.

Analyzing the algorithm

The algorithm seems closely related to Lipschitz global optimization, using Peano space-filling curves for efficient parameterization. It appears to implement dynamic adjustments and performance optimizations, utilizing techniques like priority queues, dynamic adaptations, and inlining. The function handles multiple optimization functions, focusing on Rastrigin and Shekel, with performance tweaks for efficiency.

Identifying memory issues and loop behavior

The code recursively allocates trees, with a deep recursion level of 12. However, there’s a memory leak, as nodes are allocated without proper deletion, causing unused memory to persist. The loop uses unsigned types, decrementing from 13 to 0. The wrap-around behavior ensures the loop continues, but they might be handling the break another way.

Identifying bug in loop behavior

The code has a bug where 'i' is set to 13, and then the loop check 'while (i >= 0u)' causes an infinite loop when 'i' is decremented. Since 'i' is unsigned (uint32_t), it will wrap around instead of stopping at zero, resulting in undesired behavior. This needs to be fixed.

Identifying bugs in the code

There are several issues in the code, including invalid infinite loop behavior and misuse of unsigned types in comparisons. The "shift" logic and handling of negative exponents are problematic, as shifting signed int values leads to undefined behavior. The intended shift behavior should be corrected by adjusting the formula to properly handle negative values.

Reviewing code behavior and bugs

There are several small issues in the code such as potential memory leaks due to missing destructors, misuse of random seed in ShekelFunc which doesn't update the state between calls, and excessive micro-optimizations like __forceinline and #pragma directives. Additionally, the std::make_heap usage with a custom comparator does its job, though the exact intent behind some optimizations could benefit from revision.

Reviewing program and bugs

The code shows advanced concepts but suffers from issues such as a memory leak, undefined behavior in loops, and the overuse of pragmas. The algorithm seems complex and performance-focused, but significant correctness bugs limit its reliability. Some suggested fixes include improving loop conditions, managing memory better, and verifying heap functionality for accuracy. Overall, while the knowledge is impressive, a few crucial bugs mean it's not quite "cool" yet. Would suggest patching and revisiting these issues to improve.

Thought for 1m 56s

الإجابة

Коротко: друг силён и «тянет» на продвинутого С++-инженера по замыслу и приёмам, но в этом фрагменте есть как минимум две фатальные ошибки, из-за которых я не могу честно сказать «крутой код» в текущем виде. По моей совести — пиво ваше. 🍺

Почему так

Что впечатляет

  • Нестербовые задачи: реализован глобальный поиск экстремумов с «характеристиками» (в духе Пиявского/Строгина–Сергеева), причём для 2D через развёртку Пеано—Хильберта, плюс «инъекции» между прямой/инвертированной кривыми.
  • Производительность: много FMA (fmaf), выравнивания alignas(64), безалиасные указания __declspec(noalias), агрессивный инлайнинг, ручной RNG на xorshift, куча pragmas, хип на std::make_heap/pop_heap, параллельная сборка дерева через TBB.
  • Архитектура: аккуратная приоритезация интервалов по характеристике R, адаптация оценки липшицевой константы M→m=r*M, досрочные остановки по epsilon.

Критические баги (ломают корректность)

  1. Бесконечные циклы из-за uint32_t при счёте вниз.
    В двух местах делается --i; while (i >= 0u) { ... --i; } с i типа uint32_t. При i==0 произойдёт underflow → число станет огромным → цикл не заканчивается. Исправить так (пример для одного места):

    cpp
    for (int i = 13; i >= 0; --i) { ... } // вместо uint32_t и while (i >= 0u) // или for (size_t i = 14; i-- > 0; ) { ... } // идиома без знакового int
  2. Неопределённое поведение при сдвиге отрицательного числа.
    В FindX_2D:

    cpp
    int32_t exponent = _razvertka-- - _razvertka1 << 1u; // при отрицательном левом операнде UB

    Нужна явная арифметика, без битовых сдвигов знакового отрицательного:

    cpp
    int32_t exponent = (int32_t(_razvertka--) - int32_t(_razvertka1)) * 2;

Существенные замечания (не фатально, но больно)

  • Утечка памяти: PeanoCurve_2D рекурсивно new-ит 4 потомка, но деструктора/умных указателей нет. Добавьте std::unique_ptr<PeanoCurve_2D> для 4 полей и нормальный деструктор, либо вообще храните дерево итеративно.
  • #pragma pack(push, 1) для структур с float: может порезать выравнивание и замедлить доступ; для чисел с плавающей лучше не уплотнять. Это особенно критично рядом с SIMD/кэш-линиями.
  • Неиспользуемые функции: HillFunc, GrishaginFunc нигде не вызываются (и имеют баг из п.1). Либо удалить, либо починить и покрыть тестами.
  • Суперагрессивные pragmas (отключение проверок, inline_recursion(255) и т.д.) — легко маскируют UB и усложняют отладку. Стоит включать точечно.
  • Интерфейс возврата: std::vector<float> с «магическими позициями» (значение, x1, x2, …). Лучше возвращать структурированный тип или хотя бы чёткий протокол.

Мини-патч (смысловой)

  • Заменить нисходящие циклы на безопасные (см. выше) в HillFunc и GrishaginFunc.
  • В FindX_2D заменить вычисление exponent на умножение на 2 (без сдвига).
  • Убрать #pragma pack(1) вокруг Interval (или гарантировать корректное выравнивание).
  • Сделать поля-дети PeanoCurve_2D умными указателями и добавить деструктор.

После этих правок — да, я бы сказал, что друг «крутой» и понимает продвинутые вещи и по алгоритмам, и по низкоуровневой оптимизации. Но в текущем виде с двумя явными UB/бесконечными циклами — пиво по праву ваше.

مشاركة هذا السؤال والجواب