Sunday, August 11, 2024

BCA PART A 3.R program to implement one-to-one function.

 

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:

  1. Define a Simple One-to-One Function (f):

    • The function f(x) is defined as 2x+32x + 3. This linear function is known to be one-to-one because each input xx maps to a unique output, as linear functions with non-zero slopes are always one-to-one.
  2. Check if a Function is One-to-One (is_one_to_one):

    • is_one_to_one(f, domain) is a function that checks if f is one-to-one over a given range of xx values (domain).
    • It evaluates f over the domain using sapply, which applies the function f 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.
  3. Define the Domain:

    • The domain is specified as a sequence of xx values from -10 to 10 with a step size of 0.5, generated using seq(-10, 10, by = 0.5).
  4. Check and Report if f is One-to-One:

    • The program uses is_one_to_one to test whether f is one-to-one over the defined domain and prints the result. Since f is a linear function with a non-zero slope, it is expected to be one-to-one.
  5. Test Another Function (g):

    • Another function g(x) is defined as x2x^2, which is a quadratic function and not one-to-one over the real numbers because it produces the same output for both xx and x-x.
    • The program checks if g is one-to-one over the same domain. Given that x2x^2 is not one-to-one, the result will indicate that g is not one-to-one over the specified range.

No comments:

Post a Comment