How to Compare Near Zero Using Python's math.isclose: Determining abs_tol by Unit of Measurement

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This ArticleThis article is created using an automated generation workflow leveraging generative AI. The specifications for math.isclose in the official Python documentation were verified, and the published code was executed with dummy measurement values.

Verification Status: The published code has been executed in Python 3.12. Physical sensors and measurement accuracy have not been verified.

How to Compare Near Zero Using Python's math.isclose: Determining abs_tol by Unit of Measurement

Consider a process that checks whether the scale total becomes 0 g after subtracting the weight of the box. Under the dummy measurement rules, a residual within ±0.125 g is acceptable. When implementing this condition in code,math.isclose(value, 0)Using only the default value of results in even when a non-zero residual falls within the acceptable range.FalseNear zero, specify the absolute tolerance in the same unit as the measurement.

Checking with Dummy Residuals

Save the following code to and run in the terminal. It works using only the Python 3.12 standard library, requiring no external files or hardware.check_residual.pySave the following code to and run in the terminal.python3 check_residual.pyIt works using only the Python 3.12 standard library, requiring no external files or hardware.

from math import isclose, isfinite

limit_g = 0.125
samples_g = [0.0, 0.0625, -0.125, 0.25, float("nan")]

for value_g in samples_g:
    default_result = isclose(value_g, 0.0)
    status = (
        "無効" if not isfinite(value_g)
        else "許容内" if isclose(value_g, 0.0, rel_tol=0.0, abs_tol=limit_g)
        else "許容外"
    )
    print(f"{value_g}: 既定={default_result}, 判定={status}")
0.0: 既定=True, 判定=許容内
0.0625: 既定=False, 判定=許容内
-0.125: 既定=False, 判定=許容内
0.25: 既定=False, 判定=許容外
nan: 既定=False, 判定=無効

0.0625 gis not zero, but it is included in the acceptable range for this case.-0.125 gis exactly the boundary.isclosealso returns when the difference is equal to the tolerance.TrueIf the specification dictates that the boundary is excluded, explicitly using the inequality operator makes the requirement easier to understand.abs(value_g) < limit_gIn this example, non-finite values are evaluated first, separating the display when a value falls outside the acceptable numerical range.

Why the Default Value Fails When Comparing with Zero

The relative tolerancerel_tol is the ratio multiplied by the larger of the absolute values of the two values being compared. The absolute tolerance abs_tol is a fixed width in the same unit as the values being compared.isclose uses the larger of the two tolerance widths.

If the comparison target is 0 and the residual is 0.0625, the difference is 0.0625. The width multiplied by the default relative tolerance 1e-9 is smaller than 0.0625, and the default absolute tolerance is 0. Therefore, the default determination becomes False. In the code, specify rel_tol=0.0 and perform the evaluation using the fixed width of the measurement rule 0.125 g. If the comparison target is 0 and you only want to use a fixed width, after confirming that the value is finite, writing abs(value_g) <= limit_g results in the same condition as this example.

Re-run after changing only the tolerance

limit_g = 0.125 change limit_g = 0.0625 to 0.0625. The inputs remain unchanged. The row for -0.125 remains within tolerance because it is on the boundary, whereas the row for

changes to out of tolerance. Comparing these two rows shows that the change in determination is due to the modified tolerance rather than fluctuations in the input values. In actual operations, verify the inspection specifications and product precision requirements before defining custom tolerances. Mixing units will also alter the determination. For example, if the tolerance is 0.125 g and the code input changes to mg, convert the tolerance to 125 mg as well. If the specification requires a tolerance proportional to the measured value, check the reference value for comparison and the operational rules before rel_tol determines whether it is necessary.

What to check when results do not match

First, output the input values, units, and tolerances in the same location to check them. Even if a value appears as 0, the unrounded value may still remain. In log investigation, repr(value_g) checking the values passed to the comparison prevents you from misidentifying the cause due to values rounded for display. If unexpected behavior occurs only near 0, abs_tol verify whether the specified parameter reached the call.

If missing values are mixed in, check whether missing values are replaced with 0 during conversion. 0 represents a measurement result, whereas a missing value indicates that no measurement result was obtained. Perform missing value checks according to the input format first, and allow only finite numbers in the tolerance judgment. Furthermore, this example explains comparison conditions and is not a process to eliminate floating-point rounding. If the specification requires strict decimal rounding, determine the rounding method and comparison method beforehand.

Document information

Article title
How to Compare Near Zero Using Python&apos;s math.isclose: Determining abs_tol by Unit of Measurement
Published
Updated
Source
https://papanda925.com/?p=18826&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL