简体   繁体   English

glm :: vec3精密C ++

[英]glm::vec3 precision C++

I'm creating a collision detection system in C++ using the glm library. 我正在使用glm库在C ++中创建一个碰撞检测系统。

I have an array of vertices defined as std::vector<glm::vec3> vertices and a function to calculate the maxX, y, z defined as 我有一个定义为std::vector<glm::vec3> vertices的顶点数组和一个计算maxX,y,z的函数,定义为

GLfloat AssetInstance::maxX()
{
    GLfloat max = vertices.at(0).x;

    for(glm::vec3 vertex : vertices)
        if(vertex.x > max) max = vertex.x;

    return max;
}

but if I run the following code: 但是如果我运行以下代码:

std::vector<glm::vec3> testVector;
testVector.push_back(glm::vec3(3.0500346, 1.0, 1.0));
testVector.push_back(glm::vec3(3.0500344, 2.0, 2.0));
testVector.push_back(glm::vec3(3.0500343, 3.0, 3.0));

std::cout << maxX(testVector) << std::endl;

the output is 3.05003 输出为3.05003

I thought that glm::vec3 was double and that double was more precise than that? 我认为glm::vec3doubledouble比更精确? Is there a better way to do this? 有一个更好的方法吗? My maxX isn't returning precise enough results. 我的maxX返回的结果不够精确。

Try setprecision . 尝试setprecision By default its 6 which is what youre getting. 默认情况下,它是6。

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
    std::cout << "default precision (6): " << 3.0500346 << '\n';
    std::cout << "std::precision(10):    " << std::setprecision(10) << 3.0500346 << '\n';

    return 0;
}

Output ( Coliru link ): 输出( Coliru链接 ):

clang++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
default precision (6): 3.05003
std::precision(10):    3.0500346

On another note, you're returning a GLFloat which is well a float, not a double, so no matter what glm uses, you're converting it to a float. 另一方面,您将返回一个GLFloat,它是一个float,而不是double,所以无论glm使用什么,都将其转换为float。 So ultimately, calling maxX gives you float precision, not double. 因此,最终,调用maxX会给您浮点精度,而不是两倍。

PS: Looking at the docs it looks like there is a dvec type which makes me doubt that vec uses double by default. PS:看一下文档,似乎有一个dvec类型,这使我怀疑vec默认使用double。

Nope they are single precision float ready for insertion in a VBO, so is a GLFoat by the way. 不,它们是准备插入VBO的单精度float ,顺便说一句, GLFoat也是如此。

It may be that you still get the correct index even though is won't be printed all digits. 即使不会将所有数字都打印出来,也可能仍然可以得到正确的索引。

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

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