GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Pythagorean calculation with sub-optimal numerics — CodeQL query help documentation

Pythagorean calculation with sub-optimal numerics¶

ID: py/pythagorean
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - accuracy
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

Calculating the length of the hypotenuse using the standard formula c = sqrt(a**2 + b**2) may lead to overflow if the two other sides are both very large. Even though c will not be much bigger than max(a, b), either a**2 or b**2 (or both) will. Thus, the calculation could overflow, even though the result is well within representable range.

Recommendation¶

Rather than sqrt(a**2 + b**2), use the built-in function hypot(a,b) from the math library.

Example¶

The following code shows two different ways of computing the hypotenuse. The first is a direct rewrite of the Pythagorean theorem, the second uses the built-in function.

# We know that a^2 + b^2 = c^2, and wish to use this to compute c
from math import sqrt, hypot

a = 3e154 # a^2 > 1e308
b = 4e154 # b^2 > 1e308
# with these, c = 5e154 which is less that 1e308

def longSideDirect():
    return sqrt(a**2 + b**2) # this will overflow

def longSideBuiltin():
    return hypot(a, b) # better to use built-in function

References¶

  • Python Language Reference: The hypot function

  • Wikipedia: Hypot.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.