3

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

}
AnnieFrannie
  • 53
  • 1
  • 9
  • to further the gd discussion in most of the answers, you did start off `t` as an integer, but then did maths with non-integers on it in the loop and R, Python, Ruby, et al, require different thinking about "equality" when it comes to checking two non-integer numbers given how modern computing systems store them. – hrbrmstr Jan 04 '18 at 11:56

3 Answers3

2

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!

Florian
  • 24,425
  • 4
  • 49
  • 80
1

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

tolerance = h/2;
if(min(abs(c(t%%1, t%%1-1))) < tolerance){
...
}
Arash Fotouhi
  • 1,933
  • 2
  • 22
  • 43
0

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 ..