I am trying to create a function for finding out the positive root for a quadratic equation. I have written the following code for the same but I keep getting an error stating that b not found and the following appears:
Positive_Root <- function(x,y,z){
x <- a
y <- b
z <- c
-b+sqrt(b^2-4*a*c)/2*a
}
Positive_Root(2,-1,-4)
Error in Positive_Root(2, -1, -4) : object 'b' not found
You're getting that error because you're assigning non-existent variables a, b and c to x, y and z respectively. In fact, you don't need the latter at all. You could simplify your function as follows:
Sir. Thank you for your help. Just an additional doubt. I wrote the code for n(n+1)/2 in a similar manner and didn't receive am error. Could you help in differentiating the two codes.
The difference is that the order of variable assignment is reversed. In Sum_first_n(), you are assigning x to n and x is intialized with the value 5 when you call the function.
If you change Positive_Root() as shown below it will work fine. But there's no need to create these extra variables as I explained in my previous post.
Positive_Root <- function(x, y, z) {
a <- x
b <- y
c <- z
-b + sqrt(b^2 - 4*a*c) / 2*a
}
Positive_Root(2, -1, -4)
#> [1] 6.744563
yes, and as siddharthprabhu says,
as you assign x directly to n, there is no purpose, and these are just anonymous labels, they are not special. so both of these would work