i'm trying improve speed of code, trying optimise value using 3 variables have large ranges. output uses values in middle of ranges, wasting time starting lowest possible value of each variable. want start middle value , iterate out! actual problem has thousands of lines numbers 150-650. c,h , o limits defined based on starting number, more @ central value in defined range. there way define loop work outwards want? only, quite shabby, way can think of redefine value within loop vector (e.g. 1=20, 2=21, 3=19, etc). see current code below:
set_error<-2.5 ct<-c(325.00214,325.00952,325.02004,325.02762,325.03535,325.03831,325.04588, 325.05641,325.06402,325.06766,325.07167,325.07454,325.10396) formfun<-function(x){ for(c in 1:40){ for(h in 1:80){ for(o in 1:40){ test_mass=c*12+h*1.007825+o*15.9949146-1.0072765 error<-1000000*abs(test_mass-x)/x if(error<set_error){ result<-paste("c",c,"h",h,"o",o,sep ="") return(result) break;break;break;break } } } } } old_t <- sys.time() ct2<-lapply(ct,formfun) new_t <- sys.time() - old_t # calculate difference print(new_t)
use vectorization , create closure:
formfun1_fac <- function(gr) { gr <<- gr function(x, set_error){ test_mass <- with(gr, c*12+h*1.007825+o*15.9949146-1.0072765) error <- 1000000 * abs(test_mass - x) / x ind <- which(error < set_error)[1] if (is.na(ind)) return(null) paste0("c", gr[ind, "c"],"h", gr[ind, "h"],"o", gr[ind, "o"]) } } formfun1 <- formfun1_fac(expand.grid(c = 1:40, h = 1:80, o = 1:40)) ct21 <- lapply(ct, formfun1, set_error = set_error) all.equal(ct2, ct21) #[1] true
this saves grid of combinations of c, h, o in function environment , calculates error combinations (which fast in vectorized code). first combination passes test returned.
Comments
Post a Comment