You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

Prevent math errors by carefully bounds-checking before calling functions. In particular, the following domain errors should be prevented by prior bounds-checking:

Function

Bounds-checking

acos(x), asin(x)

-1 <= x && x <= 1

atan2

x != 0 || y != 0

log, log10

x >= 0

pow(x, y)

x != 0 || y > 0

sqrt(x)

x >= 0

The calling function should take alternative action if these bounds are violated.

acos(x), asin(x)

Non-Compliant Example

The following code may produce a domain error if the argument is not in the range [-1, +1].

float x, result;

result = acos(x);

Compliant Example

The following code uses bounds checking to ensure there is not a domain error.

float x, result;

if( islessequal(x,-1) || isgreaterequal(x, 1) ){
     /* handle domain error */
}

result = acos(x);

atan2(y, x)

Non-Compliant Solution

The following code may produce a domain error if both x and y are zero.

float x, y, result;

result = atan2(y, x);

Compliant Solution

The following code tests the arguments to ensure that there is not a domain error.

float x, y, result;

if( fpclassify(x) == FP_ZERO && fpclassify(y) == FP_ZERO){
     /* handle domain error */
}

result = atan2(y, x);

log(x), log10(x)

Non-Compliant Example

The following code may produce a domain error if x is negative and a range error if x is zero.

float result, x;

result = log(x);

Compliant Example

The following code tests the suspect arguments to ensure no domain or range errors are raised.

float result, x;

if(islessequal(x, 0)){
     /* handle domain and range errors */
}

result = log(x);

pow(x,y)

Non-Compliant Example

The following code may produce a domain error if x is zero and y less than or equal to zero. A range error may also occur if x is zero and y is negative.

float x, y, result;

result = pow(x,y);

Compliant Solution

The following code tests x and y to ensure that there will be no range or domain errors.

float x, y, result;

if(fpclassify(x) == FP_ZERO && islessequal(y, 0)){
     /* handle domain error condition */
}

result = pow(x, y);

sqrt(x)

Non-Compliant Solution

The following code may produce a domain error if x is negative.

float x, result;

result = sqrt(x);

Compliant Solution

The following code tests the suspect argument to ensure no domain error is raised.

float x, result;

if(isless(x, 0)){
     /* handle domain error */
}

result = sqrt(x);

Priority: P6 Level: L2

Component

Value

Severity

1 (high)

Likelihood

2 (probable)

Remediation cost

2 (high)

References

  • No labels