Skip to content

strange differences in vector operation versus manual calculation

4 messages · Rajarshi Guha, William Dunlap, Rui Barradas +1 more

#
Hi, I'm running a calculation in two ways. The first way is to employ
vectors and evaluate a function in one go. The second way is to break
down the function into pieces and combine the pieces to the final
answer.

Algebraically, they should give me the same result. But the final
vector differs significantly. I must be missing something very
obvious, but I just cannot see it

xx <- c(-9.56305825951348, -8.20220288142583, -6.84134750333818,
-5.48049212525052,
        -4.11963674716287)
params <- structure(c(-7.9292094394, 4.9549173134, 4.738588416, 101.5743644892
                     ), .Names = c("LOG_AC50", "HILL_COEF",
"INF_ACTIVITY", "ZERO_ACTIVITY"
                          ))
yy <- params[4] + (params[3] - params[4])/(1 + 10^(params[1]-xx)^params[2])

t1 <-  10^(params[1]-xx)
t2 <- params[3] - params[4]
t3 <- (1+t1)^params[2]
t4 <- t2/t3;
t5 <- params[4] + t4

I would've expected yy and t5 to be the same; yet they are not
#
Your multistep approach corresponds to the following, which has one
more set of parentheses than you used
   yy <- params[4] + (params[3] - params[4])/((1 + 10^(params[1]-xx))^params[2])
In R lingo, both of your approaches are vectorized and you probably won't find
a huge difference in speed between them.  I would use the long approach,
as it is more understandable.  (I would also give memorable names to the
intermediate results, not t1, t2, ..., unless they really had no meaning.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
Hello,
The hardest to find errors.
Wrong manual calculation in t1, powers have precedence right to left and
before additions.

t1b <- 10^(params[1]-xx)^params[2]
t3b <- 1 + t1b
t4b <- t2/t3b
t5b <- params[4] + t4b
all.equal(yy, t5b)
TRUE

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/strange-differences-in-vector-operation-versus-manual-calculation-tp4603600p4603707.html
Sent from the R help mailing list archive at Nabble.com.
#
On Wed, May 02, 2012 at 11:42:27AM -0400, Rajarshi Guha wrote:
Hi.

The difference is caused by different placement of parenthesis.
Replacing

  (1 + 10^(params[1]-xx)^params[2])

by

  (1 + 10^(params[1]-xx))^params[2]

yields

  [1] 101.574364 101.057295  35.949148   6.428122   4.812942

which is equal to t5.

Petr Savicky.