A one-to-one function (also known as an injective function) is a function where each element in the domain maps to a unique element in the codomain. In other words, different inputs produce different outputs.
Program :
# Define a function to check if a given function is one-to-one
is_one_to_one <- function(f, domain) {
# Create a vector to store the outputs of the function
outputs <- sapply(domain, f)
# Check if all outputs are unique
if (length(outputs) == length(unique(outputs))) {
return(TRUE) # The function is one-to-one
} else {
return(FALSE) # The function is not one-to-one
}
}
# Example function 1: f(x) = x^2
f1 <- function(x) {
return(x^2)
}
# Example function 2: f(x) = x^3
f2 <- function(x) {
return(x^3)
}
# Define the domain (a set of inputs to test)
domain <- seq(-10, 10, by = 1)
# Check if the functions are one-to-one
cat("Is f(x) = x^2 one-to-one? ", is_one_to_one(f1, domain), "\n")
cat("Is f(x) = x^3 one-to-one? ", is_one_to_one(f2, domain), "\n")
Output:
Is f(x) = x^2 one-to-one? FALSE
Is f(x) = x^3 one-to-one? TRUE
=== Session Ended. Please Run the code again ===
Explanation:
Define a Simple One-to-One Function (
f
):- The function
f(x)
is defined as . This linear function is known to be one-to-one because each input maps to a unique output, as linear functions with non-zero slopes are always one-to-one.
- The function
Check if a Function is One-to-One (
is_one_to_one
):is_one_to_one(f, domain)
is a function that checks iff
is one-to-one over a given range of values (domain
).- It evaluates
f
over thedomain
usingsapply
, which applies the functionf
to each value in the domain, producing a vector of function values. - The uniqueness of these values is checked using
unique(values)
. If the number of unique function values matches the number of elements in the domain, then each input produces a unique output, confirming that the function is one-to-one.
Define the Domain:
- The domain is specified as a sequence of values from -10 to 10 with a step size of 0.5, generated using
seq(-10, 10, by = 0.5)
.
- The domain is specified as a sequence of values from -10 to 10 with a step size of 0.5, generated using
Check and Report if
f
is One-to-One:- The program uses
is_one_to_one
to test whetherf
is one-to-one over the defined domain and prints the result. Sincef
is a linear function with a non-zero slope, it is expected to be one-to-one.
- The program uses
Test Another Function (
g
):- Another function
g(x)
is defined as , which is a quadratic function and not one-to-one over the real numbers because it produces the same output for both and . - The program checks if
g
is one-to-one over the same domain. Given that is not one-to-one, the result will indicate thatg
is not one-to-one over the specified range.
- Another function
No comments:
Post a Comment