0

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?

raqu
  • 3
  • 2

2 Answers2

1

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!

Bryn
  • 27
  • 2
0

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.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
FBri
  • 41
  • 3