bhylu.com

Advertisements

C Math Functions

Use hypot and sqrt for a geometric reading while checking whether the input has a valid meaning.

How it works

math.h declares numerical functions with domain and range contracts. A negative argument to a real square root is outside its real domain; a result may also overflow or underflow. hypot computes a two-dimensional distance with better intermediate scaling than directly squaring large coordinates. Standard floating error reporting can involve errno and floating exceptions according to math_errhandling and implementation support. Check your requirements rather than assuming every bad result arrives as an ordinary numeric answer.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror math-contracts.c -o lesson -lm

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · math-contracts.c

#include <stdio.h>
#include <math.h>

int main(void) {
    double east_m = 3.0;
    double north_m = 4.0;
    double area_m2 = 81.0;
    if (!isfinite(area_m2) || area_m2 < 0.0) { return 1; }
    printf("Distance: %.1f m\n", hypot(east_m, north_m));
    printf("Square side: %.1f m\n", sqrt(area_m2));
    return 0;
}

Expected result

Distance: 5.0 m
Square side: 9.0 m

The finite nonnegative area is suitable for sqrt. The 3-4-5 distance makes the geometric result easy to check independently. Some Unix-like compiler commands need -lm after the source file to link the math library; the local review uses a toolchain whose C driver links the required runtime. Rounding a display is separate from choosing an acceptable numerical error.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements