下面是我的代码示例,试图规范化我的3点向量{5,5,5} 但是它正在打印"正常化 - 失败"在跑步的时候,有人可能会解释为什么它不会对我成功,所以我可能会试图解决它?
#include <iostream>
#include "Geometry.h"
#include <math.h>
void Normalise()
{
TVector3 _krA;//vector / mag vector = answer x y z
{
_krA.m_fX = 5;
_krA.m_fY = 5;
_krA.m_fZ = 5;
}
TVector3 _rResultant;
{
_rResultant.m_fX = (_krA.m_fX * _krA.m_fX);
_rResultant.m_fY = (_krA.m_fY * _krA.m_fY);
_rResultant.m_fZ = (_krA.m_fZ * _krA.m_fZ);
}
float _fResultFinalMag = sqrt(_rResultant.m_fX + _rResultant.m_fY + _rResultant.m_fZ);
float _fresultXMag = (_krA.m_fX / _fResultFinalMag);
float _fresultYMag = (_krA.m_fY / _fResultFinalMag);
float _fresultZMag = (_krA.m_fZ / _fResultFinalMag);
float _fNormliseTestX = 0.577350;
float _fNormliseTestY = 0.577350;
float _fNormliseTestZ = 0.577350;
if (_fNormliseTestX == _fresultXMag && _fNormliseTestY == _fresultYMag && _fNormliseTestZ == _fresultZMag)
{
std::cout << "Normalise - Success" << std::endl;
}
else
{
std::cout << "Normalise - Failed" << std::endl;
std::cout << _fresultXMag << std::endl;
std::cout << _fresultYMag << std::endl;
std::cout << _fresultZMag << std::endl;
std::cout << _fResultFinalMag << std::endl;
}
}
答案 0 :(得分:7)
您的代码打印"Failed"
的原因是因为您正在使用float
完全比较==
值。浮点数据类型通常不会精确地存储值,而是以一定的精度存储它们。此外,它们会受到舍入误差的影响,进一步加剧了您对这些值进行的计算。
阅读有关"Why doesn’t my floating-point comparison work?"的C ++常见问题解答条目,以获得详细解释。
您有一个选择,就是使用epsilon进行比较:
float epsilon = 0.0001; // or whatever accuracy you require
if (fabs(_fNormliseTestX - _fresultXMag) < epsilon) {
// _fNormliseTestX and _fresultXMag are considered equal
}