In: Computer Science
Please answer the following by coding in R with comments ! Thank you!!!
Evaluation of a square root is achieved using the sqrt() function, but a warning will be issued when the argument is negative. Consider the following code which is designed to test whether a given value is positive before checking whether the square root of the value is less than 5.
testValue <-7
(testValue > 0) & (sqrt(testValue) < 5)
## [1] TRUE
testValue <--7
(testValue > 0) & (sqrt(testValue) < 5)
## Warning in sqrt(testValue): NaNs produced
## [1] FALSE
Modify the code so that it continues to give the correct answer but without the warning.
Let's start with understanding the syntax of sqrt() function in R programming language, the syntax is shown below -
sqrt(numeric_expression) # Return type is integer
where, numeric_expression can be a positive or negative value.
Keeping this in mind, let's modify the code to get rid of warning.
Modified code :
testValue <-7
if (testValue > 0){ # when
testValue>0
if(sqrt(testValue) < 5)
{
TRUE # when testValue>0 and sqrt(testValue)<5
}
else
{
FALSE # when testValue>0 but sqrt(testValue)>5
}
} else {
FALSE # when testValue<0
}
## [1] TRUE
testValue <--7
if (testValue > 0){ # when testValue>0
if(sqrt(testValue) < 5)
{
TRUE # when testValue>0 and sqrt(testValue)<5
}
else
{
FALSE # when testValue>0 but sqrt(testValue)>5
}
} else {
FALSE # when testValue<0
}
## [1] FALSE
CONCLUSION :
Using if-else conditional statements, it is easy to get the
desired output for various test conditions. This modified code uses
nested if-else statements to check each possible outcome of the
given condition and prints the valid output.