# Python math.atan2() Examples

The following are 30 code examples of math.atan2(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module , or try the search function .
Example #1
 Source Project: dcs   Author: pydcs   File: mapping.py    License: GNU Lesser General Public License v3.0 7 votes  ```def heading_between_points(x1, y1, x2, y2):
"""Returns the angle between 2 points in degrees.

:param x1: x coordinate of point 1
:param y1: y coordinate of point 1
:param x2: x coordinate of point 2
:param y2: y coordinate of point 2
:return: angle in degrees
"""
def angle_trunc(a):
while a < 0.0:
a += math.pi * 2
return a
deltax = x2 - x1
deltay = y2 - y1
return math.degrees(angle_trunc(math.atan2(deltay, deltax))) ```
Example #2
 Source Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    License: Apache License 2.0 6 votes  ```def distance(origin, destination):
"""Determine distance between 2 sets of [lat,lon] in km"""

lat1, lon1 = origin
lat2, lon2 = destination

a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

return d ```
Example #3
 Source Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env.py    License: BSD 2-Clause "Simplified" License 6 votes  ```def _get_observation(self):
world_translation_minitaur, world_rotation_minitaur = (
self._pybullet_client.getBasePositionAndOrientation(
world_translation_ball, world_rotation_ball = (
self._pybullet_client.getBasePositionAndOrientation(self._ball_id))
minitaur_translation_world, minitaur_rotation_world = (
self._pybullet_client.invertTransform(world_translation_minitaur,
world_rotation_minitaur))
minitaur_translation_ball, _ = (
self._pybullet_client.multiplyTransforms(minitaur_translation_world,
minitaur_rotation_world,
world_translation_ball,
world_rotation_ball))
distance = math.sqrt(minitaur_translation_ball**2 +
minitaur_translation_ball**2)
angle = math.atan2(minitaur_translation_ball,
minitaur_translation_ball)
self._observation = [angle - math.pi / 2, distance]
return self._observation ```
Example #4
 Source Project: symbolator   Author: kevinpt   File: cairo_backend.py    License: MIT License 6 votes  ```def draw_marker(self, name, mp, tp, weight, c):
if name in self.markers:
m_shape, ref, orient, units = self.markers[name]

c.save()
c.translate(*mp)
if orient == 'auto':
angle = math.atan2(tp-mp, tp-mp)
c.rotate(angle)
elif isinstance(orient, int):
c.rotate(angle)

if units == 'stroke':
c.scale(weight, weight)

c.translate(-ref, -ref)

self.draw_shape(m_shape)
c.restore() ```
Example #5
 Source Project: pointnet-registration-framework   Author: vinits5   File: test_utils.py    License: MIT License 6 votes  ```def rotm2eul(m):
""" m (3x3, rotation matrix) --> rotation m = Rz*Ry*Rx
"""
c = math.sqrt(R[0,0] * R[0,0] +  R[1,0] * R[1,0])

singular = c < 1e-6
if not singular :
x = math.atan2(R[2,1] , R[2,2])
y = math.atan2(-R[2,0], c)
z = math.atan2(R[1,0], R[0,0])
else :
x = math.atan2(-R[1,2], R[1,1])
y = math.atan2(-R[2,0], c)
z = 0

return numpy.array([x, y, z])

#EOF ```
Example #6
 Source Project: NeuroKit   Author: neuropsychology   File: ecg_simulate.py    License: MIT License 6 votes  ```def _ecg_simulate_derivsecgsyn(t, x, rr, ti, sfint, ai, bi):

ta = math.atan2(x, x)
r0 = 1
a0 = 1.0 - np.sqrt(x ** 2 + x ** 2) / r0

ip = np.floor(t * sfint).astype(int)
w0 = 2 * np.pi / rr[min(ip, len(rr) - 1)]
# w0 = 2*np.pi/rr[ip[ip <= np.max(rr)]]

fresp = 0.25
zbase = 0.005 * np.sin(2 * np.pi * fresp * t)

dx1dt = a0 * x - w0 * x
dx2dt = a0 * x + w0 * x

# matlab rem and numpy rem are different
# dti = np.remainder(ta - ti, 2*np.pi)
dti = (ta - ti) - np.round((ta - ti) / 2 / np.pi) * 2 * np.pi
dx3dt = -np.sum(ai * dti * np.exp(-0.5 * (dti / bi) ** 2)) - 1 * (x - zbase)

dxdt = np.array([dx1dt, dx2dt, dx3dt])
return dxdt ```
Example #7
 Source Project: Localization   Author: kamalshadi   File: geometry.py    License: MIT License 6 votes  ```def map(self, p, inv=False):
# cartesian to lat/lon
# if inv is true lat/lon to cartesian
R = self.R
if not inv:
ed = R * (vec(p - self.c).norm())
ed = point(ed.dx, ed.dy, ed.dz)
lon = math.atan2(ed.y, ed.x)
lat1 = math.acos(abs(ed.z) / R)
if ed.z > 0:
lat = math.pi / 2 - lat1
else:
lat = -(math.pi / 2 - lat1)
return point(lon, lat) * 180 / math.pi
if inv:
p = p * math.pi / 180
z = R * math.sin(p.y)
y = R * math.cos(p.y) * math.sin(p.x)
x = R * math.cos(p.y) * math.cos(p.x)
return point(x, y, z) ```
Example #8
 Source Project: honeybee   Author: ladybug-tools   File: euclid.py    License: GNU General Public License v3.0 6 votes  ```def get_euler(self):
t = self.x * self.y + self.z * self.w
if t > 0.4999:
heading = 2 * math.atan2(self.x, self.w)
attitude = math.pi / 2
bank = 0
elif t < -0.4999:
heading = -2 * math.atan2(self.x, self.w)
attitude = -math.pi / 2
bank = 0
else:
sqx = self.x ** 2
sqy = self.y ** 2
sqz = self.z ** 2
heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
1 - 2 * sqy - 2 * sqz)
attitude = math.asin(2 * t)
bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
1 - 2 * sqx - 2 * sqz)
Example #9
 Source Project: codimension   Author: SergeySatskiy   File: profgraph.py    License: GNU General Public License v3.0 6 votes  ```def addArrow(self, painterPath, startX, startY, endX, endY):
http://kapo-cpp.blogspot.com/2008/10/drawing-arrows-with-cairo.html
"""
arrowLength = 12.0

angle = math.atan2(endY - startY, endX - startX) + math.pi
arrowX1 = endX + arrowLength * math.cos(angle - arrowDegrees)
arrowY1 = endY + arrowLength * math.sin(angle - arrowDegrees)
arrowX2 = endX + arrowLength * math.cos(angle + arrowDegrees)
arrowY2 = endY + arrowLength * math.sin(angle + arrowDegrees)

painterPath.moveTo(endX, endY)
painterPath.lineTo(arrowX1, arrowY1)
painterPath.moveTo(endX, endY)
painterPath.lineTo(arrowX2, arrowY2) ```
Example #10
 Source Project: codimension   Author: SergeySatskiy   File: importsdgmgraphics.py    License: GNU General Public License v3.0 6 votes  ```def addArrow(self, painterPath, startX, startY, endX, endY):
http://kapo-cpp.blogspot.com/2008/10/drawing-arrows-with-cairo.html
"""
arrowLength = 12.0

angle = math.atan2(endY - startY, endX - startX) + math.pi
arrowX1 = endX + arrowLength * math.cos(angle - arrowDegrees)
arrowY1 = endY + arrowLength * math.sin(angle - arrowDegrees)
arrowX2 = endX + arrowLength * math.cos(angle + arrowDegrees)
arrowY2 = endY + arrowLength * math.sin(angle + arrowDegrees)

painterPath.moveTo(endX, endY)
painterPath.lineTo(arrowX1, arrowY1)
painterPath.moveTo(endX, endY)
painterPath.lineTo(arrowX2, arrowY2) ```
Example #11
 Source Project: spatialpixel   Author: awmartin   File: behaviors.py    License: MIT License 6 votes  ```def apply(self, fish, state):
if state['closecount'] == 0:
return

center = state['center']
distance_to_center = dist(
center, center,
fish.position, fish.position
)

if distance_to_center > self.parameters['threshold']:
angle_to_center = math.atan2(
fish.position - center,
fish.position - center
)
fish.turnrate += (angle_to_center - fish.direction) / self.parameters['weight']
fish.speed += distance_to_center / self.parameters['speedfactor'] ```
Example #12
 Source Project: syntrax   Author: kevinpt   File: syntrax.py    License: MIT License 6 votes  ```def cairo_draw_arrow(head, tail, fill, c):
width = c.get_line_width()
c.save()
angle = math.atan2(dy,dx)
c.rotate(angle)
c.scale(width, width)

# Now positioned to draw arrow at 0,0 with point facing right
apath = [(-4,0), (-4.5,2), (0,0)]

mirror = [(x,-y) for x, y in reversed(apath[1:-1])] # Mirror central points
apath.extend(mirror)

c.move_to(*apath)
for p in apath[1:]:
c.line_to(*p)
c.close_path()

c.set_source_rgba(*fill)
c.fill()

c.restore() ```
Example #13
 Source Project: gw2pvo   Author: markruys   File: netatmo_api.py    License: MIT License 5 votes  ```def haversine_distance(self, lat1, lon1, lat2, lon2):
R = 6371.0088
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance * 1000 ```
Example #14
 Source Project: sixcells   Author: oprypin   File: util.py    License: GNU General Public License v3.0 5 votes  ```def angle(a, b=None):
"""Angle between two items: 0 if b is above a, tau/4 if b is to the right of a...
If b is not supplied, this becomes the angle between (0, 0) and a."""
try:
ax, ay = a
except TypeError:
ax, ay = a.x(), a.y()
if b is None:
return _math.atan2(ax, -ay)
try:
bx, by = b
except TypeError:
bx, by = b.x(), b.y()
return _math.atan2(bx-ax, ay-by) ```
Example #15
 Source Project: dump1090-tools   Author: mutability   File: adsb-polar.py    License: ISC License 5 votes  ```def latlngup_to_relxyz(c,l):
# this converts WGS84 (lat,lng,alt) to a rotated ECEF frame
# where the earth center is still at the origin
# but (clat,clng,calt) has been rotated to lie on the positive X axis

clat,clng,calt = c
llat,llng,lalt = l

# rotate by -clng around Z to put C on the X/Z plane
# (this is easy to do while still in WGS84 coordinates)
llng = llng - clng

# find angle between XY plane and C
cx,cy,cz = latlngup_to_ecef((clat,0,calt))
a = math.atan2(cz,cx)

# convert L to (rotated around Z) ECEF
lx,ly,lz = latlngup_to_ecef((llat,llng,lalt))

# rotate by -a around Y to put C on the X axis
asin = math.sin(-a)
acos = math.cos(-a)
rx = lx * acos - lz * asin
rz = lx * asin + lz * acos

return (rx, ly, rz)

# calculate range, bearing, elevation from C to L ```
Example #16
 Source Project: dump1090-tools   Author: mutability   File: adsb-polar.py    License: ISC License 5 votes  ```def range_bearing_elevation(c,l):
# rotate C onto X axis
crx, cry, crz = latlngup_to_relxyz(c,c)
# rotate L in the same way
lrx, lry, lrz = latlngup_to_relxyz(c,l)

# Now we have cartesian coordinates with C on
# the X axis with ground plane YZ and north along +Z.

dx, dy, dz = lrx-crx, lry-cry, lrz-crz
rng = math.sqrt(dx*dx + dy*dy + dz*dz)
bearing = (360 + 90 - rtod(math.atan2(dz,dy))) % 360
elev = rtod(math.asin(dx / rng))

return (rng, bearing, elev) ```
Example #17
 Source Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    License: ISC License 5 votes  ```def latlngup_to_relxyz(c,l):
# this converts WGS84 (lat,lng,alt) to a rotated ECEF frame
# where the earth center is still at the origin
# but (clat,clng,calt) has been rotated to lie on the positive X axis

clat,clng,calt = c
llat,llng,lalt = l

# rotate by -clng around Z to put C on the X/Z plane
# (this is easy to do while still in WGS84 coordinates)
llng = llng - clng

# find angle between XY plane and C
cx,cy,cz = latlngup_to_ecef((clat,0,calt))
a = math.atan2(cz,cx)

# convert L to (rotated around Z) ECEF
lx,ly,lz = latlngup_to_ecef((llat,llng,lalt))

# rotate by -a around Y to put C on the X axis
asin = math.sin(-a)
acos = math.cos(-a)
rx = lx * acos - lz * asin
rz = lx * asin + lz * acos

return (rx, ly, rz)

# great circle distance from C to L, assuming spherical geometry (~0.3% error)
# from http://www.movable-type.co.uk/scripts/latlong.html ("haversine formula") ```
Example #18
 Source Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    License: ISC License 5 votes  ```def gc_distance(c,l):
# great circle distance (assumes spherical geometry!)
lat1 = dtor(c)
lat2 = dtor(l)
delta_lat = lat2 - lat1
delta_lon = dtor(c - l)

a = math.sin(delta_lat/2) * math.sin(delta_lat/2) + math.cos(lat1) * math.cos(lat2) * math.sin(delta_lon/2) * math.sin(delta_lon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return MEAN_R * c ```
Example #19
 Source Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    License: ISC License 5 votes  ```def range_bearing_elevation_from(c):
# build a function that calculates ranges, bearing, elevation from C
clat,clng,calt = c

# rotate by -clng to put C on the XZ plane
# find angle between XY plane and C
cx,cy,cz = latlngup_to_ecef((clat,0,calt))
a = math.atan2(cz,cx)

# rotate by -a around Y to put C on the X axis
asin = math.sin(-a)
acos = math.cos(-a)

crx = cx * acos - cz * asin
cry = cy                         # should be zero
crz = cx * asin + cz * acos      # should be zero

def rbe(l):
# rotate L into our new reference frame
llat,llng,lalt = l
# rotate by -clng, convert to ECEF
lx,ly,lz = latlngup_to_ecef((llat,llng - clng,lalt))

# rotate by -a around Y
lrx = lx * acos - lz * asin
lry = ly
lrz = lx * asin + lz * acos

# Now we have cartesian coordinates with C on
# the +X axis, ground plane YZ, north along +Z.

dx, dy, dz = lrx-crx, lry-cry, lrz-crz
slant = math.sqrt(dx*dx + dy*dy + dz*dz)             # true line-of-sight range
bearing = (360 + 90 - rtod(math.atan2(dz,dy))) % 360 # bearing around X axis
elev = rtod(math.asin(dx / slant))                   # elevation from horizon (YZ plane)
horiz_range = math.sqrt(dy*dy + dz*dz)               # distance projected onto YZ (ground/horizon plane); something like ground distance if the Earth was flat
return (slant, horiz_range, bearing, elev, (lrx,lry,lrz))

return rbe

# calculate true range, bearing, elevation from C to L ```
Example #20
 Source Project: quadcopter-simulation   Author: hbd730   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes  ```def RotToRPY(R):
phi = asin(R[1,2])
theta = atan2(-R[0,2]/cos(phi),R[2,2]/cos(phi))
psi = atan2(-R[1,0]/cos(phi),R[1,1]/cos(phi))
return phi, theta, psi ```
Example #21
 Source Project: jawfish   Author: war-and-code   File: turtle.py    License: MIT License 5 votes  ```def towards(self, x, y=None):
"""Return the angle of the line from the turtle's position to (x, y).

Arguments:
x -- a number   or  a pair/vector of numbers   or   a turtle instance
y -- a number       None                            None

call: distance(x, y)         # two coordinates
--or: distance((x, y))       # a pair (tuple) of coordinates
--or: distance(vec)          # e.g. as returned by pos()
--or: distance(mypen)        # where mypen is another turtle

Return the angle, between the line from turtle-position to position
specified by x, y and the turtle's start orientation. (Depends on
modes - "standard" or "logo")

Example (for a Turtle instance named turtle):
>>> turtle.pos()
(10.00, 10.00)
>>> turtle.towards(0,0)
225.0
"""
if y is not None:
pos = Vec2D(x, y)
if isinstance(x, Vec2D):
pos = x
elif isinstance(x, tuple):
pos = Vec2D(*x)
elif isinstance(x, TNavigator):
pos = x._position
x, y = pos - self._position
result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
result /= self._degreesPerAU
return (self._angleOffset + self._angleOrient*result) % self._fullcircle ```
Example #22
 Source Project: jawfish   Author: war-and-code   File: turtle.py    License: MIT License 5 votes  ```def heading(self):
""" Return the turtle's current heading.

No arguments.

Example (for a Turtle instance named turtle):
>>> turtle.left(67)
67.0
"""
x, y = self._orient
result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
result /= self._degreesPerAU
return (self._angleOffset + self._angleOrient*result) % self._fullcircle ```
Example #23
 Source Project: jawfish   Author: war-and-code   File: turtle.py    License: MIT License 5 votes  ```def shapetransform(self, t11=None, t12=None, t21=None, t22=None):
"""Set or return the current transformation matrix of the turtle shape.

Optional arguments: t11, t12, t21, t22 -- numbers.

If none of the matrix elements are given, return the transformation
matrix.
Otherwise set the given elements and transform the turtleshape
according to the matrix consisting of first row t11, t12 and
second row t21, 22.
Modify stretchfactor, shearfactor and tiltangle according to the
given matrix.

Examples (for a Turtle instance named turtle):
>>> turtle.shape("square")
>>> turtle.shapesize(4,2)
>>> turtle.shearfactor(-0.5)
>>> turtle.shapetransform()
(4.0, -1.0, -0.0, 2.0)
"""
#console.log("shapetransform")
if t11 is t12 is t21 is t22 is None:
return self._shapetrafo
m11, m12, m21, m22 = self._shapetrafo
if t11 is not None: m11 = t11
if t12 is not None: m12 = t12
if t21 is not None: m21 = t21
if t22 is not None: m22 = t22
if t11 * t22 - t12 * t21 == 0:
raise TurtleGraphicsError("Bad shape transform matrix: must not be singular")
self._shapetrafo = (m11, m12, m21, m22)
alfa = math.atan2(-m21, m11) % (2 * math.pi)
sa, ca = math.sin(alfa), math.cos(alfa)
a11, a12, a21, a22 = (ca*m11 - sa*m21, ca*m12 - sa*m22,
sa*m11 + ca*m21, sa*m12 + ca*m22)
self._stretchfactor = a11, a22
self._shearfactor = a12/a22
self._tilt = alfa
self._update() ```
Example #24
 Source Project: networkx_viewer   Author: jsexauer   File: graph_canvas.py    License: GNU General Public License v3.0 5 votes  ```def _spline_center(self, x1, y1, x2, y2, m):
"""Given the coordinate for the end points of a spline, calcuate
the mipdoint extruded out m pixles"""
a = (x2 + x1)/2
b = (y2 + y1)/2
beta = (pi/2) - atan2((y2-y1), (x2-x1))

xa = a - m*cos(beta)
ya = b + m*sin(beta)
return (xa, ya) ```
Example #25
 Source Project: me-ica   Author: ME-ICA   File: test_euler.py    License: GNU Lesser General Public License v2.1 5 votes  ```def crude_mat2euler(M):
''' The simplest possible - ignoring atan2 instability '''
r11, r12, r13, r21, r22, r23, r31, r32, r33 = M.flat
return math.atan2(-r12, r11), math.asin(r13), math.atan2(-r23, r33) ```
Example #26
 Source Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 5 votes  ```def CDF(self, x):
return 0.5 + math.atan2(x-self.loc, self.s)*(1.0/math.pi) ```
Example #27
 Source Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes  ```def genpy(self, paramTypes, args, pos):
return "math.atan2({0}, {1})".format(*args) ```
Example #28
 Source Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes  ```def __call__(self, state, scope, pos, paramTypes, x, y):
return math.atan2(x, y) ```
Example #29
 Source Project: simnibs   Author: simnibs   File: eeg_positions.py    License: GNU General Public License v3.0 5 votes  ```def findPolarAngle(self, point):
point_transf = point - self.C
point_transf = point_transf.dot(self.transf_matrix)
x = point_transf
y = point_transf
# print x,y
# if abs(y)<1e-3: y = 1e-3
angle = math.atan2(y, x)
if angle < (-3.1415 / 2.0): angle += 2 * 3.1415

return angle

# finds the coordinate that's a given fraction of the arch ```
Example #30
 Source Project: dronekit-python   Author: dronekit   File: guided_set_speed_yaw.py    License: Apache License 2.0 5 votes  ```def get_bearing(aLocation1, aLocation2):
"""
Returns the bearing between the two LocationGlobal objects passed as parameters.

This method is an approximation, and may not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py
"""
off_x = aLocation2.lon - aLocation1.lon
off_y = aLocation2.lat - aLocation1.lat
bearing = 90.00 + math.atan2(-off_y, off_x) * 57.2957795
if bearing < 0:
bearing += 360.00
return bearing; ```