From d9a3541fd75ecec3b8b89222231c2edfcab7264f Mon Sep 17 00:00:00 2001 From: cianciosa Date: Wed, 1 Jul 2026 18:36:31 -0400 Subject: [PATCH] Disable reductions of sqrt(c*v) when c is a negative real. This causes NaN that would normally be avoided if the variable v is also negative, --- graph_framework/math.hpp | 16 ++++++++++++---- graph_tests/math_test.cpp | 6 ++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/graph_framework/math.hpp b/graph_framework/math.hpp index 4ce01ba..f22f3f6 100644 --- a/graph_framework/math.hpp +++ b/graph_framework/math.hpp @@ -88,16 +88,24 @@ namespace graph { ap2->get_right(), ap2->get_y_scale(), ap2->get_y_offset()); } -// Handle cases like sqrt(c*x) where c is constant or cases like -// sqrt((x^a)*y). +// Handle cases like sqrt(c*x) where c is constant or cases like sqrt((x^a)*y). +// Note that we need to disable this reduction C is a negative real. auto am = multiply_cast(this->arg); if (am.get()) { if (pow_cast(am->get_left()).get() || am->get_left()->is_constant() || pow_cast(am->get_right()).get() || am->get_right()->is_constant()) { - return sqrt(am->get_left()) * - sqrt(am->get_right()); + if constexpr (jit::complex_scalar) { + return sqrt(am->get_left()) * + sqrt(am->get_right()); + } else { + if (am->get_left()->is_constant() && + !am->get_left()->evaluate().is_negative()) { + return sqrt(am->get_left()) * + sqrt(am->get_right()); + } + } } } diff --git a/graph_tests/math_test.cpp b/graph_tests/math_test.cpp index ac612c1..3a0f65a 100644 --- a/graph_tests/math_test.cpp +++ b/graph_tests/math_test.cpp @@ -112,6 +112,12 @@ void test_sqrt() { assert(!sqrt_var->is_constant() && "Did not expect a constant."); assert(sqrt_var->is_all_variables() && "Expected a variable."); assert(sqrt_var->is_power_like() && "Expected a power like."); + + if constexpr (!jit::complex_scalar) { + auto sqrtnegvar = graph::sqrt(-x_var); + assert(graph::sqrt_cast(sqrtnegvar) && + "Expected no reduction."); + } } //------------------------------------------------------------------------------