0

Sometimes Octave shows a number that is very close to zero, instead of "real" zero.

e.g.:

>> sin(pi)
ans =   1.2246e-016

I understand that it's due to floating point arithmetic problems, and so on, but it's annoying...

Is there a way to get the expected 0 instead of some almost-zero value?

EDIT

A more real-life example is this:

>> cos(pi) + i*sin(pi)
ans = -1.0000e+000 + 1.2246e-016i

Applying some rounding function to the result won't help, and I don't want to insert rounding functions inside the calculation.

Isn't some way to tell Octave "to be less precise"?

Other, less sophisticated tools (like SpeedCrunch) do it "out-of-the-box":

cos(pi) + i*sin(pi)
= -1
Zvika
  • 1,542
  • 2
  • 17
  • 21
  • 1
    Possible duplicate of [GNU Octave, round a number to units precision](https://stackoverflow.com/questions/11386033/gnu-octave-round-a-number-to-units-precision) –  Sep 04 '17 at 17:04

1 Answers1

3

Its a bit ambiguous to define

very close to zero

But however you can use round function, which rounds to nearest integer

round(sin(pi))

Of course this will not work with sin function as the all return values are between [-1 1].

So you can define your generic function to truncate the number if the it is less than a certain range.

function retval = bound (num,boundval)

  if  (abs(num) < boundval)
    retval = 0;
  else
    retval = num;
  endif
endfunction

This function will set return zero if the num argument is in range of [-bound bound]

You can use it for example as

bound(myvar,0.001);

Mostafa
  • 468
  • 3
  • 16