【问题标题】:Why doesn't the if-function check for integers?为什么 if 函数不检查整数?
【发布时间】:2018-06-13 22:33:16
【问题描述】:

所以我尝试用时间步长 h 进行递归计算,时间为 t。 我想要第二个 if 函数(在 while 循环中)检查时间 t 是否为整数。当 t=9 时它适用于第一个循环,但之后当 t=8,7,6,... 时它会忽略,依此类推。现在我只是不明白为什么。 如果有任何帮助或想法,我将不胜感激!

h=1/12;
b1=10000;
b2=25000*0.15*12; #45000
mu_10=0.004183;
mu_12=0.002136;
mu_20=0.0050196;
mu_21=0.005;

V1_start=h*(-b1);   
V2_start=h*(b2);

t_vektor<-c(10);
V1_vektor<-c(V1_start);
V2_vektor<-c(V2_start);

t=as.integer(9);

while (t>0){ 

  if(t==1){
    V1_ny=V1_start+h*(-log(1.04)*V1_start+b1-mu_10*V1_start+mu_12*(V2_start-V1_start));
  }else{
    V1_ny=V1_start+h*(-log(1.04)*V1_start-mu_10*V1_start+mu_12*(V2_start-V1_start));
  }

  V2_ny=V2_start+h*(-log(1.04)*V2_start+b2-mu_20*V2_start+mu_21*(V1_start-V2_start));


  if(round(t)==t){
    V1_vektor<-c(V1_vektor,V1_ny);
    V2_vektor<-c(V2_vektor,V2_ny);
    t_vektor<-c(t_vektor,t);

    V2_start=V2_ny;
    V1_start=V1_ny;
    t=t-h;

  }else{
    V2_start=V2_ny;
    V1_start=V1_ny;
    t=t-h; 
    print(t)
  }

}

【问题讨论】:

  • 为了在大多数答案中进一步讨论 gd,您确实从 t 作为整数开始,但随后在循环和 R、Python、Ruby、等人,考虑到现代计算系统如何存储它们,在检查两个非整数时需要对“平等”有不同的思考。

标签: r if-statement integer


【解决方案1】:

这与数字的存储方式有关,另请参阅here。

您的案例的示例,请参阅以下代码的输出:

t = 9
h=1/12
for(i in 1:12)
{
  t=t-h
}
print(t) # 8
print(t==8) # FALSE
all.equal(t,8) # TRUE

在你的情况下,尝试:

isTRUE(all.equal(round(t),t))

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    而不是if(round(t)==t) 使用:

    tolerance = h/2;
    if(min(abs(c(t%%1, t%%1-1))) < tolerance){
    ...
    }
    

    【讨论】:

    • 嗯,这似乎可以解决问题!但是你能解释一下为什么 if(round(t)==t) 不起作用吗?
    • 查看@Florian 的回答。他完美地解释了这一点。
    【解决方案3】:

    您在 t 上进行测试,但在打印之前更改了 t,然后通过“t=t-h”行打印它; 所以你看不到女巫的价值被测试了..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多