Joe 5
Joe 5

Reputation: 19

Function with two arguments in R

I am trying to better understand functions and found an example online but can't get it to work. I want to solve an equation a, and have two arguments v and r. v= 10 and r=3. Here is my code. What am I missing? Thanks for your insights.

solve <- function(r=3,v=10) {
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4)) 
}
return(a)

Based on inputs. Here is the updated code. But looks like the result is not accurate.

solve <- function(r,v){
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4)) 
return(a)
}
solve(3,10)

R is giving me a result of 810.4933. But the example says the result is 29.9906. Here is the formula for A: enter image description here

Upvotes: 0

Views: 126

Answers (1)

r2evans
r2evans

Reputation: 160447

You need to know the order of operations within math expressions. If you read ?Ops (kind of obscure, granted), you'll see

       2. Group '"Ops"':
            • '"+"', '"-"', '"*"', '"/"', '"^"', '"%%"', '"%/%"'
            • '"&"', '"|"', '"!"'
            • '"=="', '"!="', '"<"', '"<="', '">="', '">"'

Which suggests that * and / are consecutive. Unfortunately, your denominator of

... / pi^2*r^4

is being interpreted as

(... / pi^2) * (r^4)

which brings r^4 into the numerator.

Add parens to enforce the order of operations.

.../(pi^2*r^4)

Upvotes: 1

Related Questions