AutoLISP fix function returns incorrect integer
问题:
Why does the AutoLISP Fix function sometimes return the wrong results?
When I get the Z coordinate of a lwpolyline vertex and then fix it to the
nearest integer, it occasionally returns the wrong results. To illustrate this,
if the returned value is reported as 50.0, in some cases
(fix num) returns a value of 49.
解答:
This example demonstrates an inescapable internal problem with precision.
Sometimes AutoCAD's 16 significant digits fail to account for some of the
floating point part of the number that is being fixed.
To illustrate: AutoCAD reports a 50.0 zvalue is returned by the entget of a
specific polyline vertex.However, the following manipulation indicates that
the actual numeric value is different:
(setq num (- 50 zvalue))
(rtos num 2 16)
This shows a difference of "0.0000000000000071".Thus, there is a small
difference in the floating point part of the numbers. This difference results in
the return of 49 from (fix). This is because the actual value is
49.9999999999999928, but the full 16-digit float is evaluated only when the
(fix) command examines the value to the right of the decimal.Otherwise AutoCAD
sees just 14 decimal places (i.e., 49.99999999999999) and rounds the number to
50.0.
A workaround is to compare the returned value with an interpreted value and,
based on the result, fix the desired number:
(if (= num (atof (rtos num)))
(fix num)
(fix (atof (rtos num)))
)
页:
[1]