AnnieFrannie
AnnieFrannie

Reputation: 53

Why doesn't the if-function check for integers?

So I'm trying to do a recursive calculation with time-steps h, and the time is t. I want the second if-function (in the while-loop) to check if the time t is an integer. It works for the first loop when t=9, but after that it ignores when t=8,7,6,... and so on. And right now I just don't understand why. I would be very grateful for any help or ideas!

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)
  }

}

Upvotes: 3

Views: 59

Answers (3)

MrSmithGoesToWashington
MrSmithGoesToWashington

Reputation: 1076

You make your test on t, but you change t before printing it by the line "t=t-h"; So you don't see the value witch was tested ..

Upvotes: 0

Florian
Florian

Reputation: 25385

This has to do with the way numbers are stored, see also here.

An example for your case, see the output of the following code:

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

in your case, try:

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

Hope this helps!

Upvotes: 2

Arash Fotouhi
Arash Fotouhi

Reputation: 2103

Instead of if(round(t)==t) use:

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

Upvotes: 1

Related Questions