0
import math class Vector(): vA = [3.183, 7.627] def magnitude(vector): sum = 0 i = 0 while i < len(vector): sum += vector[i] i += 1 return math.sqrt(sum) def unitVector(vector): print( 1 / (magnitude(vA) * vA)) 

I'm attempting to code some linear algebra and calculate the unit vectors for the vector 'vA' stated above. When I run the code I get NameError: global name 'magnitude' is not defined. I do not understand why I am having an issue with simply calling one function from another.

I'm a beginner with python and I'm assuming I have a misunderstanding about classes and functions, but I have looked through the documentation and cannot find the answer I am looking for.

2
  • Instance methods need a self parameter Commented May 20, 2016 at 5:00
  • Sidenote: the numpy library is probably better to do linear algebra calculations Commented May 20, 2016 at 5:02

1 Answer 1

1

You have several errors in your code:

  • def magnitude(vector) should be def magnitude(self, vector)
  • def unitVector(vector) should be def unitVector(self, vector)
  • magnitude(vA) should be self.magnitude(vA)

EDIT:

A better way of writing your class would be to use OOP concepts in Python, so you do not have to pass vector as a function argument if you make it an instance variable.

Your class can be rewrote like this:

import math class Vector(): def __init__(self, vector): self.vector = vector def magnitude(self): sum = 0 i = 0 while i < len(self.vector): sum += self.vector[i] i += 1 return math.sqrt(sum) def unitVector(self): print( 1 / (self.magnitude() * self.vector)) vA = [3.183, 7.627] vec = Vector(vA) vec.unitVector() 

Be aware that it does not work. Because in unitVector, Python doesn't know how to multiply a float by a list (self.magnitude() returns a float and self.vector is a list). You probably want to rework this part.

Sign up to request clarification or add additional context in comments.

5 Comments

Magnitude doesn't really need a parameter, though
None of the method really need one
@cricket_007 if the methods do not need parameters then how would I call them on a specific array?
If you use Python OOP the right way, then you won't have problems calling the methods with any array you want. I edited my answer.
@T.Claverie Having only experience in simple java, I was confused about how exactly to use init, but I think your answer has cleared it up for me. I'll work on the incompatible types and hopefully get the answer I'm looking for. I appreciate your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.