双精度C ++ [英] double precision C++

查看:140
本文介绍了双精度C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为double的精度导致了这个问题,就像在相似的帖子中描述的那样,但是我想知道是否有办法达到正确的结果。我使用的函数模板比​​较两个参数,如果它们相等,则返回true。

  template< class T> 
bool eq(T one,T two)
{
if(one == two)
return true;
else
返回false;



$ b $ p $它可以和eq(0.8,0.8)一起使用,但是不起作用与eq(0.8 * 0.2,0.16)。正如我所提到的,我认为它必须做双精度,因为它也适用于int eq(8 * 2,16)。

解决方案

首先,您应该阅读以下文章中的一篇(或两篇):每台计算机科学家应该知道浮点运算浮点运算的危险。 p>

如果您正在寻找您的模板的解决方案,我会建议使用 T == double T == float template specialization c>。


I think the precision of double is causing that problem, as it was described in similiar posts, but I would like to know if there is a way to achieve correct result. I'm using function template which compares two parameters and returns true if they are equal.

template <class T>
bool eq(T one, T two)
{
  if (one == two)
    return true;
  else
    return false;
}

It works with eq (0.8,0.8), but it doesn't work with eq (0.8*0.2,0.16). As I mentioned I assume it has to do with double precision as it also works fine with int eq(8*2,16).

解决方案

First you should read one (or both) of these articles: What Every Computer Scientist Should Know About Floating-Point Arithmetic and The Perils of Floating Point.

If you are looking for a solution for your template, I would suggest using template specialization for the cases where T==double and T==float.

这篇关于双精度C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆