# [SciPy-user] floating point pedagogical problem

Ryan Krauss ryanlists@gmail....
Mon Jun 25 19:08:57 CDT 2007

```Thanks Robert.  The clip solution is much less frightening than my 10
mysterious lines of code.

On 6/25/07, Robert Kern <robert.kern@gmail.com> wrote:
> Ryan Krauss wrote:
> > I have  a floating point issue that is forcing me to teach my students
> > more python/computer science than I want to:
> >
> > In [36]: temp
> > Out[36]: NumPy array, format: long
> > [-1.         -0.83045267 -0.64773663 -0.45185185 -0.24279835 -0.02057613
> >   0.21481481  0.46337449  0.72510288  1.        ]
> >
> > In [37]: arccos(temp)
> > Out[37]: NumPy array, format: long
> > [                  nan            2.55071609            2.27540616
> >             2.03963643            1.81604581            1.59137391
> >             1.35429411            1.08899693            0.75961255
> >                    nan]
> >
> >
> > We are doing a robotics problem involving inverse kinematics where
> > they need to take the arccos and arcsin of some vectors.  The problem
> > is that
> > In [38]: eps=1e-15
> >
> > In [39]: -1-eps < temp[0] < -1+eps
> > Out[39]: True
> >
> > So, my current solution is to check for theta +/- 1 +/- eps problems like this:
> >
> > tempout = []
> > for item in temp:
> >       if -1-eps<item<-1+eps:
> >               tempout.append(-1.0)
> >       elif 1-eps<item<1+eps:
> >               tempout.append(1.0)
> >       else:
> >               tempout.append(item)
> > tempout = array(tempout)
> >
> > Is there a better way?
>
> clip(temp, -1.0, 1.0)
>
> That will silently allow obviously bogus values like 1.5, but you may not care
> overmuch for the problem.
>
> > Is making arccos and arcsin check for +/-1 +/-
> > eps reasonable?
>
> I don't think so. eps may not be the appropriate fuzz-factor for the problem.
>
> > Or should I give a lecture on floating point evils?
>
> Are they using floating point? If so, then yes, they need to know about the
> little buggers.
>
> For domain issues like this, though, it's simple enough to say that floating
> point introduces inaccuracies and sometimes functions that have restricted
> domains require some extra care to clip inputs to the domain.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>  that is made terrible by our own mad attempt to interpret it as though it had
>  an underlying truth."
>   -- Umberto Eco
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>
```