3

i am trying to examining the round-off error associated with sin(x) using Octave I get these numbers:

>> single(sin(10))
ans = -0.544021129608154

>> sin(10)
ans = -0.544021110889370

>> (single(sin(10))) - (sin(10))
ans = 0

which should be : -1.8718784 × 10^-8

I typed in: format long but it still gives me zero and I have no idea how to get the actual answer.

user35053
  • 33
  • 6
  • 2
    You should really tag this as Octave rather than MATLAB; this appears to be an Octave-only problem. – beaker Feb 04 '16 at 23:51

2 Answers2

3

This works for me in MATLAB 2014.

>> single(sin(10))-sin(10)

ans =

 -1.8719e-08

Try double(single(sin(10)))-sin(10) instead maybe? But I don't know why your result wouldn't work.

(Note: this post was originally tagged MATLAB, which is why I said it was weird.)

rlbond
  • 65,341
  • 56
  • 178
  • 228
  • I'm getting the same result as the OP in Octave, however your workaround gives the correct results. (I was working on the same solution myself.) :) – beaker Feb 04 '16 at 23:50
  • I am using octave so maybe that is why I am getting zeros but I thought it would be the same. Hope that is the problem. Thanks. – user35053 Feb 04 '16 at 23:52
3

When performing a computation between single and double, the return value will have the class with the lowest precision. This means that when you do

single (sin (10)) - sin (10)

your result will be of class single. Note that this is the same for operations between different integer types; you will get back the one with less precision. This means that before the subtraction happens, your double gets cast to single too.

From the other answers, it seems that Matlab actually performs the computations with doubles. This is very odd because Matlab also returns a single like Octave. It must convert the single to double, perform the computation in double, and the cast it to single. Anyway, I have reported an Octave bug for Matlab compatibility.

carandraug
  • 12,938
  • 1
  • 26
  • 38