Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make 0 divided by 0 results in NaN consistently #2253

Merged
merged 1 commit into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ static jv f_multiply(jq_state *jq, jv input, jv a, jv b) {
static jv f_divide(jq_state *jq, jv input, jv a, jv b) {
jv_free(input);
if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {
if (jv_number_value(b) == 0.0)
if (jv_number_value(b) == 0.0 && jv_number_value(a) != 0.0)
return type_error2(a, b, "cannot be divided because the divisor is zero");
jv r = jv_number(jv_number_value(a) / jv_number_value(b));
Comment on lines +383 to 385
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is actually problematic because division by 0 is unspecified for all values in C, so 0.0/0.0 will be undefined behaviour.
If we want to make 0/0 return nan, we should hardcode that case.

diff --git a/src/builtin.c b/src/builtin.c
index 09ffc04..1b4aec2 100644
--- a/src/builtin.c
+++ b/src/builtin.c
@@ -383,8 +383,13 @@ static jv f_multiply(jq_state *jq, jv input, jv a, jv b) {
 static jv f_divide(jq_state *jq, jv input, jv a, jv b) {
   jv_free(input);
   if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {
-    if (jv_number_value(b) == 0.0 && jv_number_value(a) != 0.0)
-      return type_error2(a, b, "cannot be divided because the divisor is zero");
+    if (jv_number_value(b) == 0.0) {
+      if (jv_number_value(a) != 0.0)
+        return type_error2(a, b, "cannot be divided because the divisor is zero");
+      jv_free(a);
+      jv_free(b);
+      return jv_number(NAN);
+    }
     jv r = jv_number(jv_number_value(a) / jv_number_value(b));
     jv_free(a);
     jv_free(b);

jv_free(a);
Expand Down
5 changes: 5 additions & 0 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -1556,6 +1556,11 @@ try (1/.) catch .
0
"number (1) and number (0) cannot be divided because the divisor is zero"

0/0, (0 as $x | $x/0) | isnan
0
true
true

try (1%.) catch .
0
"number (1) and number (0) cannot be divided (remainder) because the divisor is zero"
Expand Down