编译器从 float 转换为 double 时的奇怪行为 [英] Strange behavior when compiler converts from float to double

查看:31
本文介绍了编译器从 float 转换为 double 时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

float foo[3];

在 ino 文件中,我必须将其中一个作为输入发送到 PID.

In the ino file I have to send one of them to the PID as input.

double output;
PID myPID(&input, &output, &target, 1, 0.0, 1.1, DIRECT);
...
void loop(){
  input =foo[2];   
  myPID.Compute();
  Serial.print(output); //output: "nan"
...
}

PID 如下:

PID::PID(double* Input, double* Output, double* Setpoint,
        double Kp, double Ki, double Kd, int ControllerDirection)

它可以编译,但 PID outvalue 的输出是 nan.

It compiles but the output of the PID outvalue is nan.

但是,如果我将输入设置为 -1.2,则它可以工作.

However if I set the input to -1.2 then it works.

void loop(){
      input =foo[2];  
      input = -1.2;
      myPID.Compute();
      Serial.print(output); //output: "1200"
    ...
    }

我该如何解决这个问题?编译器应该自动转换双倍浮点数.就像在 Mega 2560 中一样.我也试过:input =double(foo[2]); 没有任何成功.

How can I fix this? The compiler should auto convert double the float. As in Mega 2560. I have also tried: input =double(foo[2]); without any success.

  Serial.print(foo[2]);  //Prints -9.2
  foo[2] = -9.2;         // I manually set foo[2] to -9.2  
  xAngle = foo[2];
  xPID.Compute();        //Computes perfectly.

我必须补充一点,foo 在自定义库中.这太奇怪了.有人知道这个吗?

I have to add that foo is in a custom library. This is so strange. Anyone got a clue about this?

推荐答案

  • 首先,所有 AVR 双打都是浮点数,如此处所述此处.这使得双精度与 Arduino Mega 2560 上的浮点数相同.您可以通过比较 sizeof(double);sizeof(float); 来验证这一点,它们都将返回 4.
  • 其次,如果你想将一种类型转换为另一种类型,语法是(targetType)sourceType,所以如果你做那种事情,你的任务应该是这样的

    • First of all, all AVR doubles are floats as described here or here. This makes doubles be the same as floats on Arduino Mega 2560. You can verify this by comparing sizeof(double); and sizeof(float); both will return 4.
    • Secondly, if you want to cast one type to another the syntax is (targetType)sourceType, so if you do that sort of a thing, your assignment should look like this

      input =(double)foo[2];
      

    •     input =(double)(foo[2]);
      

      然而,这在这种情况下无关紧要,因为双打和浮动是相同的.

      However, this is irrelevant in this case since doubles and floats are identical.

      我认为问题很可能来自这样一个事实,即根据您设置的参数,您的 PID 控制器不喜欢您在 foo[2] 中的任何值.在分配 input = foo[2]; 之前,您是否尝试过 foo[2]=-1.2 ?

      I think most likely the problem comes from the fact that your PID controller does not like whatever value you have in foo[2] given the parameters you set. Have you tried foo[2]=-1.2 before assigning input = foo[2];?

      这篇关于编译器从 float 转换为 double 时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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