Home > Blockchain >  How abs() works for 2D vector
How abs() works for 2D vector

Time:07-10

I can't understand how abs() function works with pos() method from Turle graphics:

from turtle import *
while True:
    forward(200)
    left(170)
    print(str(abs(pos())) "\t\t" str(pos()))
    if abs(pos()) < 1:
        break

The abs() function change vector like this:

(3.04,34.73) >> 34.862297099063255

Is there any mathematical explanation of this?

CodePudding user response:

abs(x) returns either the absolute value for x if x is an integer or a custom value for x if x implements an abs()-method. In your case, pos() is returning an object of type Vec2D, which implements the abs()-method like the following:

def __abs__(self):
    return (self[0]**2   self[1]**2)**0.5

So the value returned by abs(x) is here the length of this vector. In this case, this makes sense also because that way you get a one-dimensional representation of this vector.

CodePudding user response:

Hey that looks to be taking the scalar quantity of the vector, I.e its taking the distance from the origin as a double. the formula for that is the Pythagorean theorem (sqrt(a^2 b^2)) hope that helps!

  • Related