Skip to content

Fix Equal and value comparison for double and float types #3088

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

Merged
merged 4 commits into from
Feb 6, 2025

Conversation

josesimoes
Copy link
Member

@josesimoes josesimoes commented Feb 5, 2025

Description

  • Add data types to switch that performs value comparison.
  • Add code to deal with edge cases for Equal comparison for NaN (differs from equality operator).
  • Fix hash code computation to deal with signed NaN and zero values.
  • Fix numeric comparison of NaN values for both double and float (C types).

Motivation and Context

How Has This Been Tested?

Screenshots

Types of changes

  • Improvement (non-breaking change that improves a feature, code or algorithm)
  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • New feature (non-breaking change which adds functionality to code)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Config and build (change in the configuration and build system, has no impact on code or features)
  • Dev Containers (changes related with Dev Containers, has no impact on code or features)
  • Dependencies/declarations (update dependencies or assembly declarations and changes associated, has no impact on code or features)
  • Documentation (changes or updates in the documentation, has no impact on code or features)

Checklist

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced floating-point value comparisons to accurately handle NaN values, ensuring consistent behavior in numerical operations.
  • Chores

    • Introduced new macros for floating-point checks and made minor formatting adjustments for improved code clarity.

@nfbot nfbot added the Type: bug label Feb 5, 2025
Copy link

coderabbitai bot commented Feb 5, 2025

Walkthrough

This pull request modifies the CLR_RT_HeapBlock.cpp file to enhance the ObjectsEqual method by adding support for floating-point data types, specifically DATATYPE_R4 and DATATYPE_R8. The updated logic allows for proper equality checks for these types, including handling NaN values as equal, which were not previously addressed. Additionally, a new macro for __isnanf is introduced in nanoPAL_NativeDouble.h, and minor formatting changes were made, including adjustments to comments.

Changes

File Change Summary
src/CLR/.../CLR_RT_HeapBlock.cpp Enhanced ObjectsEqual method to handle DATATYPE_R4 and DATATYPE_R8 for floating-point comparisons; minor formatting changes
src/PAL/Include/nanoPAL_NativeDouble.h Added macro definition for __isnanf to support single-precision floating-point checks.

Assessment against linked issues

Objective Addressed Explanation
Correct floating-point comparison handling for DATATYPE_R4 and DATATYPE_R8 (#1563)
Ensure proper handling of NaN values in comparisons (#1563)
Align floating-point equality checks with expected .NET behavior (#1563)
Expand macro definitions for floating-point checks (#1397)

Suggested labels

Area: Common libs

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/CLR/Core/CLR_RT_HeapBlock.cpp (1)

1657-1722: LGTM! Comprehensive floating-point comparison implementation.

The implementation correctly handles all floating-point comparison cases including NaN and infinite values, using safe comparison functions. The code aligns with IEEE 754 floating-point comparison semantics.

Consider adding a comment block explaining the special case handling and post-processing in the interpreter:

+// Special case handling for floating-point comparisons:
+// 1. NaN comparisons return 1 (post-processed to 0 in interpreter)
+// 2. Infinite value comparisons return 0 (post-processed to 1 in interpreter)
+// 3. Regular comparisons use isgreater/isless for safe IEEE 754 compliant comparison
 case DATATYPE_R4:
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb91c37 and a51de63.

📒 Files selected for processing (1)
  • src/CLR/Core/CLR_RT_HeapBlock.cpp (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (1)
src/CLR/Core/CLR_RT_HeapBlock.cpp (1)

1334-1335: LGTM! Floating-point types are now correctly handled.

The addition of DATATYPE_R4 and DATATYPE_R8 to the switch statement ensures that floating-point comparisons are properly handled by routing them through the Compare_Values method, aligning with the behavior of the full .NET framework.

@josesimoes josesimoes force-pushed the fix-1563 branch 2 times, most recently from 01a3ff3 to 791d967 Compare February 5, 2025 17:18
@josesimoes josesimoes changed the title Fix ObjectsEqual for double and float types Fix Equal and value comparison for double and float types Feb 5, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/CLR/Core/CLR_RT_HeapBlock.cpp (1)

1104-1119: LGTM! The hash code calculation for floating-point types now correctly handles special cases.

The changes ensure that NaN values and both zeros (positive and negative) have the same hash code, aligning with .NET behavior.

Consider adding a reference to the .NET documentation in the comments:

-            // ensure that NaN and both zeros have the same hash code
+            // ensure that NaN and both zeros have the same hash code
+            // See: https://learn.microsoft.com/en-us/dotnet/api/system.double.gethashcode

Also applies to: 1130-1143

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd588a5 and 0d12ed4.

📒 Files selected for processing (1)
  • src/CLR/Core/CLR_RT_HeapBlock.cpp (6 hunks)
🔇 Additional comments (1)
src/CLR/Core/CLR_RT_HeapBlock.cpp (1)

1364-1386: LGTM! The floating-point comparison now correctly handles NaN values.

The changes ensure that NaN values are considered equal to each other, aligning with .NET behavior. The implementation correctly handles both single-precision (R4) and double-precision (R8) floating-point types.

The added link to the .NET documentation is particularly helpful for understanding the rationale behind treating NaN values as equal:
https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-double-equals?WT.mc_id=DT-MVP-5004179#nan

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/CLR/Core/CLR_RT_HeapBlock.cpp (3)

1105-1117: LGTM! Consider a minor optimization for hash code generation.

The implementation correctly handles special cases for R4 (single-precision) by ensuring that NaN and both zeros (positive and negative) have the same hash code, aligning with .NET behavior.

Consider combining the conditions to reduce branching:

-if ((signBit && (__isnanf(ptr->NumericByRef().r4) || ptr->NumericByRef().r4 == 0)))
+if (__isnanf(ptr->NumericByRef().r4) || (signBit && ptr->NumericByRef().r4 == 0))

1130-1143: LGTM! Consider a minor optimization for hash code generation.

The implementation correctly handles special cases for R8 (double-precision) by ensuring that NaN and both zeros (positive and negative) have the same hash code, aligning with .NET behavior.

Consider combining the conditions to reduce branching:

-if ((signBit && (__isnand(ptr->NumericByRef().r8) || (double)ptr->NumericByRef().r8 == 0)))
+if (__isnand(ptr->NumericByRef().r8) || (signBit && (double)ptr->NumericByRef().r8 == 0))

1364-1386: LGTM! Consider adding documentation for special cases.

The implementation correctly handles floating-point comparisons, including the special case where NaN equals NaN, aligning with .NET behavior. The link to the official documentation is a good practice.

Consider adding a comment block to explain the special cases:

 // edge cases, in .NET a NaN is equal to another NaN
 // https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-double-equals?WT.mc_id=DT-MVP-5004179#nan
+// Special cases for floating-point comparison:
+// 1. NaN == NaN returns true (unlike IEEE 754)
+// 2. -0.0 == +0.0 returns true
+// 3. All other comparisons follow IEEE 754
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0d12ed4 and 153c086.

📒 Files selected for processing (2)
  • src/CLR/Core/CLR_RT_HeapBlock.cpp (6 hunks)
  • src/PAL/Include/nanoPAL_NativeDouble.h (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (1)
src/PAL/Include/nanoPAL_NativeDouble.h (1)

16-17: Verify the correctness of using _isnan for both single and double precision.

The implementation reuses _isnan for both single-precision (__isnanf) and double-precision (__isnand) NaN checks. While this might work in most cases, it's important to verify that _isnan correctly handles both precisions.

josesimoes and others added 3 commits February 6, 2025 12:43
- Add data types to switch that performs value comparison.
- Fix comparison of NaN values for both double and float (C types).
Automated fixes for code style.
Automated fixes for code style.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/CLR/Core/CLR_RT_HeapBlock.cpp (3)

1104-1119: Use __signbitf for float type instead of __signbitd.

While the implementation correctly handles NaN and zero values for R4 type, it's using __signbitd which is meant for double precision. For better type safety and clarity, use __signbitf for float type.

-            int signBit = __signbitd(ptr->NumericByRef().r4);
+            int signBit = __signbitf(ptr->NumericByRef().r4);

1130-1143: Remove redundant casts to double.

The implementation correctly handles NaN and zero values for R8 type. However, there are redundant casts to double as r8 is already a double precision value.

-            int signBit = __signbitd((double)ptr->NumericByRef().r8);
+            int signBit = __signbitd(ptr->NumericByRef().r8);

-            if (__isnand((double)ptr->NumericByRef().r8) || (signBit && (double)ptr->NumericByRef().r8 == 0))
+            if (__isnand(ptr->NumericByRef().r8) || (signBit && ptr->NumericByRef().r8 == 0))

1376-1386: Remove redundant casts to double in R8 comparison.

The implementation correctly handles NaN equality for R8 type. However, there are redundant casts to double that can be removed.

-            if (__isnand((double)pArgLeft.NumericByRefConst().r8) && __isnand((double)pArgRight.NumericByRefConst().r8))
+            if (__isnand(pArgLeft.NumericByRefConst().r8) && __isnand(pArgRight.NumericByRefConst().r8))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 153c086 and 54add5c.

📒 Files selected for processing (2)
  • src/CLR/Core/CLR_RT_HeapBlock.cpp (6 hunks)
  • src/PAL/Include/nanoPAL_NativeDouble.h (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/PAL/Include/nanoPAL_NativeDouble.h
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (1)
src/CLR/Core/CLR_RT_HeapBlock.cpp (1)

1364-1375: LGTM! Correct implementation of NaN equality for R4.

The implementation correctly handles NaN equality for R4 type, aligning with .NET behavior where NaN values are considered equal to other NaN values. The code is well-documented with a reference to official documentation.

@josesimoes josesimoes merged commit 1b5dd62 into nanoframework:main Feb 6, 2025
25 checks passed
@josesimoes josesimoes deleted the fix-1563 branch February 6, 2025 19:53
josesimoes added a commit that referenced this pull request Mar 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants