Repository navigation
Commit 51af998
authored
fix(base): angle_std returned nan for identical angles (#254)
## The problem
`angle_std` of a set of identical angles can return `nan`:
```python
>>> import numpy as np
>>> from spatialmath.base import angle_std
>>> angle_std(np.full(100, -2.9))
nan # RuntimeWarning: invalid value encountered in sqrt
```
`R`, the length of the mean of the unit vectors, is at most 1, but
rounding can make it `1 + 2e-16`. Then `-2 * log(R)` is a tiny negative
number and its square root is `nan`. The answer should be 0.
I counted 33 failures in 378 combinations of angle (`-3.1` to `3.1`) and
sample size (1 to 100).
## The fix
Clamp the value under the square root at zero. `R == 0` still gives
`inf`, as before.
## Test
`test_angle_std_identical_angles` runs the 378 combinations and fails on
the old code and passes now. The existing `test_angle_stats` still
passes (24 tests in the file).
Found while reviewing a particle filter change in the Robotics Toolbox
that uses `angle_std`.1 parent 0bb35fa commit 51af998
2 files changed
Lines changed: 16 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
698 | 698 | | |
699 | 699 | | |
700 | 700 | | |
701 | | - | |
| 701 | + | |
| 702 | + | |
| 703 | + | |
| 704 | + | |
702 | 705 | | |
703 | 706 | | |
704 | 707 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
7 | 7 | | |
8 | 8 | | |
9 | 9 | | |
| 10 | + | |
10 | 11 | | |
11 | 12 | | |
12 | 13 | | |
| |||
397 | 398 | | |
398 | 399 | | |
399 | 400 | | |
| 401 | + | |
| 402 | + | |
| 403 | + | |
| 404 | + | |
| 405 | + | |
| 406 | + | |
| 407 | + | |
| 408 | + | |
| 409 | + | |
| 410 | + | |
| 411 | + | |
400 | 412 | | |
401 | 413 | | |
402 | 414 | | |
| |||
0 commit comments