Home > database >  I need Assistance with my Function Problem, I am getting zero for all my answers
I need Assistance with my Function Problem, I am getting zero for all my answers

Time:05-18

This is the problem I am trying to solve:

Write a function my_is_orthogonal(v1,v2, tol), where v1 and v2 are column vectors of the same size and tol is a scalar value strictly larger than 0. The output should be 1 if the angle between v1 and v2 is within tol of π/2; that is, |π/2−θ < tol|, and 0 otherwise. You may assume that v1 and v2 are column vectors of the same size, and that tol is a positive scalar.

This is my code:

def my_is_orthogonal(v1,v2,tol):

    v1 = np.array((1,2,3))
    v2 = np.array((2,3,4))
    tol = print("Input a number larger than 0!")>0
    
    unit_vector1 = v1 / np.linalg.norm(v1)
    unit_vector2 = v2 / np.linalg.norm(v2)
    dot_product = np.dot(unit_vector1, unit_vector2)
    angle = np.arccos(dot_product)

    
    if abs((pi/2)-angle)<tol:
        print("1")
    else:
        print("0")
    return my_is_orthogonal

These are the cases for which i should test my code:

Test cases for problem 2
a = np.array([[1], [0.001]])
b = np.array([[0.001], [1]])
output should be: 1
my_is_orthogonal(a,b, 0.01)
output should be: 0
my_is_orthogonal(a,b, 0.001)
output should be: 0
a = np.array([[1], [0.001]])
b = np.array([[1], [1]])
my_is_orthogonal(a,b, 0.01)
output should be: 1
a = np.array([[1], [1]])
b = np.array([[-1], [1]])
my_is_orthogonal(a,b, 1e-10)*

But for all my cases the Answer im getting is zero "0"

CodePudding user response:

Here's a fixed version of your code.

There were quite some nonsensicalities:

  • You overwrote v1 and v2 at the start of the function with a constant. Secondly, you overwrote tol with print(...) > 0, i.e. false (and as a side effect always printed an error message). In other words, your function was always constant.
  • You shouldn't have a function print 1 or 0, but return a value. (You previously returned the function itself, which sounds like a MATLABism, but doesn't make sense in Python).
  • You weren't showing your import of pi (it's not a built-in in Python), so I replaced that with np.pi.
  • Your test vectors weren't of the correct shape.
import numpy as np

def my_is_orthogonal(v1, v2, tol):
    assert tol > 0, "Tol must be > 0"

    unit_vector1 = v1 / np.linalg.norm(v1)
    unit_vector2 = v2 / np.linalg.norm(v2)
    dot_product = np.dot(unit_vector1, unit_vector2)
    angle = np.arccos(dot_product)

    return abs((np.pi / 2) - angle) < tol


a = np.array([1, 0.001])
b = np.array([0.001, 1])
c = np.array([1, 1])
d = np.array([1, -1])
assert my_is_orthogonal(a,b, 0.01)
assert not my_is_orthogonal(a, b, 0.001)
assert not my_is_orthogonal(a, c, 0.01)
assert my_is_orthogonal(c, d, 1e-10)
  • Related