简体   繁体   English

八度-显示“真实”零

[英]Octave - show "real' zero

Sometimes Octave shows a number that is very close to zero, instead of "real" zero. 有时八度显示的数字非常接近零,而不是“实数”零。

eg: 例如:

>> 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? 有没有办法获得预期的0而不是一些几乎为零的值?

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"? 是否没有办法告诉Octave“不太精确”?

Other, less sophisticated tools (like SpeedCrunch) do it "out-of-the-box": 其他不那么复杂的工具(例如SpeedCrunch)可以“开箱即用”地进行操作:

cos(pi) + i*sin(pi)
= -1

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]. 当然,这对于sin函数将不起作用,因为所有返回值都在[-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] 如果num参数在[-bound bound]范围内,则此函数将设置返回零。

You can use it for example as 您可以使用它作为例如

bound(myvar,0.001);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM