The log2() function is used to calculate the base-2 logarithm of a number or a vector of numbers.
Syntax
log2(number)
Parameters
number: It is a number whose logarithm base 2 must be calculated.
Return value
It returns the logarithm of a number to the base 2.
- If the number is zero, then this function outputs -Inf.
- If the number is negative, this function outputs NaN and a warning message.
Example 1: Basic usage
log2(11)
log2(1)
Output
[1] 3.459432
[1] -Inf
Example 2: Handling Zero and Negative Values
# Logarithm of zero
log2_zero <- log2(0)
print(log2_zero) # Expected output: -Inf
# Logarithm of a negative number
log2_negative <- log2(-1)
print(log2_negative) # Expected output: NaN
Output
[1] -Inf
Warning message:
NaNs produced
[1] NaN
Example 3: Using vector
vec <- c(1, 2, 4, 8)
cat("The vector sequence is: ")
cat(log2(vec), "\n")
Output
The vector sequence is: 0 1 2 3
Example 4: Plotting
Open the Rstudio and write the following code, and it will create a graph.
vec <- seq(0, 1, by = 0.1)
plot(data, log2(vec), typ = "l", col = "red")
Output
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.