def lines_len_in_circle(r, font_size=12, letter_width=7.2):
"""Return the amount of chars that fits each line in a circle according to
its radius *r*
Doctest:
.. doctest::
>>> lines_len_in_circle(20)
[2, 5, 2]
"""
lines = 2 * r // font_size
positions = [
x + (font_size // 2) * (-1 if x <= 0 else 1)
for x in text_y(lines)
]
return [
int(2 * r * cos(asin(y / r)) / letter_width)
for y in positions
]
python类asin()的实例源码
def get_new_coords(init_loc, distance, bearing):
""" Given an initial lat/lng, a distance(in kms), and a bearing (degrees),
this will calculate the resulting lat/lng coordinates.
"""
R = 6378.1 #km radius of the earth
bearing = math.radians(bearing)
init_coords = [math.radians(init_loc[0]), math.radians(init_loc[1])] # convert lat/lng to radians
new_lat = math.asin( math.sin(init_coords[0])*math.cos(distance/R) +
math.cos(init_coords[0])*math.sin(distance/R)*math.cos(bearing))
new_lon = init_coords[1] + math.atan2(math.sin(bearing)*math.sin(distance/R)*math.cos(init_coords[0]),
math.cos(distance/R)-math.sin(init_coords[0])*math.sin(new_lat))
return [math.degrees(new_lat), math.degrees(new_lon)]
def calc_pitch():
""" Calculates pitch value"""
acc_x = read_acc_x()
acc_y = read_acc_y()
acc_z = read_acc_z()
acc_x_norm = acc_x / math.sqrt(acc_x * acc_x + acc_y * acc_y + acc_z * acc_z)
try:
pitch = math.asin(acc_x_norm)
return pitch
except Exception as e:
logging.debug(e)
return 0
def calc_roll():
""" Calculates roll value """
acc_x = read_acc_x()
acc_y = read_acc_y()
acc_z = read_acc_z()
acc_y_norm = acc_y / math.sqrt(acc_x * acc_x + acc_y * acc_y + acc_z * acc_z)
try:
roll = -math.asin(acc_y_norm / math.cos(calc_pitch()))
return roll
except Exception as e:
logging.debug(e)
return 0
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
Taken from: http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
def draw_circle(radius_in_meters, center_point, steps=15):
"""
get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false
"""
steps = steps if steps > 15 else 15
center = [center_point['coordinates'][1], center_point['coordinates'][0]]
dist = (radius_in_meters / 1000) / 6371
# convert meters to radiant
rad_center = [number2radius(center[0]), number2radius(center[1])]
# 15 sided circle
poly = []
for step in range(0, steps):
brng = 2 * math.pi * step / steps
lat = math.asin(math.sin(rad_center[0]) * math.cos(dist) +
math.cos(rad_center[0]) * math.sin(dist) * math.cos(brng))
lng = rad_center[1] + math.atan2(math.sin(brng) * math.sin(dist)
* math.cos(rad_center[0]), math.cos(dist) - math.sin(rad_center[0]) * math.sin(lat))
poly.append([number2degree(lng), number2degree(lat)])
return {"type": "Polygon", "coordinates": [poly]}
def destination_point(point, brng, dist):
"""
Calculate a destination Point base on a base point and a distance
Keyword arguments:
pt -- polygon geojson object
brng -- an angle in degrees
dist -- distance in Kilometer between destination and base point
return destination point object
"""
dist = float(dist) / 6371 # convert dist to angular distance in radians
brng = number2radius(brng)
lon1 = number2radius(point['coordinates'][0])
lat1 = number2radius(point['coordinates'][1])
lat2 = math.asin(math.sin(lat1) * math.cos(dist) +
math.cos(lat1) * math.sin(dist) * math.cos(brng))
lon2 = lon1 + math.atan2(math.sin(brng) * math.sin(dist) *
math.cos(lat1), math.cos(dist) - math.sin(lat1) * math.sin(lat2))
lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi # normalise to -180 degree +180 degree
return {'type': 'Point', 'coordinates': [number2degree(lon2), number2degree(lat2)]}
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine formula
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.asin(math.sqrt(a))
# 6367 km is the radius of the Earth
km = 6367 * c
latency = km / 200000
return latency
def eubik(pos, armid="rgt"):
"""
compute the euristic waist rotation
ew = euristic waist
:param pos: object position
:return: waistangle in degree
author: weiwei
date: 20170410
"""
anglecomponent1 = 0
try:
anglecomponent1 = math.asin(80/np.linalg.norm(pos[0:2]))
except:
pass
waistangle = (math.atan2(pos[1], pos[0]) + anglecomponent1)*180/math.pi
if armid=="lft":
waistangle = 180.0-2*math.atan2(pos[0], pos[1])*180.0/math.pi-waistangle
return waistangle
def eubik(pos, armid="rgt"):
"""
compute the euristic waist rotation
ew = euristic waist
:param pos: object position
:return: waistangle in degree
author: weiwei
date: 20170410
"""
anglecomponent1 = 0
try:
anglecomponent1 = math.asin(80/np.linalg.norm(pos[0:2]))
except:
pass
waistangle = (math.atan2(pos[1], pos[0]) + anglecomponent1)*180/math.pi
if armid=="lft":
waistangle = 180.0-2*math.atan2(pos[0], pos[1])*180.0/math.pi-waistangle
return waistangle
def compute_hdistance(lon1,lat1,lon2,lat2):
lon1 = float(lon1)
lat1 = float(lat1)
lon2 = float(lon2)
lat2 = float(lat2)
radLat1 = rad(lat1)
radLat2 = rad(lat2)
a = radLat1 - radLat2
b = rad(lon1) - rad(lon2)
s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b/2),2)))
s = s * 6378.137
s = round(s * 10000) / 10
return s
### return odistance ############################
def angular_position(texcoord):
up = texcoord[0]
v = texcoord[1]
# correct for hemisphere
if up>=0.5:
u = 2.0*(up-0.5)
else:
u = 2.0*up
# ignore points outside of circles
if ((u-0.5)*(u-0.5) + (v-0.5)*(v-0.5))>0.25:
return None, None
# v: 0..1-> vp: -1..1
phi = math.asin(2.0*(v-0.5))
# u = math.cos(phi)*math.cos(theta)
# u: 0..1 -> upp: -1..1
u = 1.0-u
theta = math.acos( 2.0*(u-0.5) / math.cos(phi) )
if up<0.5:
theta = theta-math.pi
return (theta,phi)
def quat2euler(q):
"""
Returns the euler representation (in degrees) of a quaternion. Note, the
heading is wrapped between 0-360 degrees.
In:
[q0 q1 q2 q3] = [w x y z]
out:
(roll, pitch, yaw) in degrees
"""
q0, q1, q2, q3 = q
roll = atan2(2.0*q2*q3-2.0*q0*q1, 2.0*q0*q0+2.0*q3*q3-1.0)
pitch = -asin(2.0*q1*q3+2.0*q0*q2)
heading = atan2(2.0*q1*q2-2.0*q0*q3, 2.0*q0*q0+2.0*q1*q1-1.0)
heading = heading if heading <= 2*pi else heading-2*pi
heading = heading if heading >= 0 else heading+2*pi
return map(rad2deg, (roll, pitch, heading))
def rotation(self):
'''Extracts Euler angles of rotation from this matrix.
This attempts to find alternate rotations in case of gimbal lock,
but all of the usual problems with Euler angles apply here.
All Euler angles are in radians.
'''
(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) = self._v
rotY = D = math.asin(c)
C = math.cos(rotY)
if (abs(C) > 0.005):
trX = k/C ; trY = -g/C ; rotX = math.atan2(trY, trX)
trX = a/C ; trY = -b/C ; rotZ = math.atan2(trY, trX)
else:
rotX = 0
trX = f ; trY = e ; rotZ = math.atan2(trY, trX)
return V(rotX,rotY,rotZ)
def __sub__(self, other):
"""Subtraction.
Args:
other: the LatLng which this LatLng is subtracted by.
Returns:
the great circle distance between two LatLng objects as computed
by the Haversine formula.
"""
assert isinstance(other, LatLng)
lat_rad = math.radians(self._lat)
lng_rad = math.radians(self._lng)
other_lat_rad = math.radians(other.latitude)
other_lng_rad = math.radians(other.longitude)
dlat = lat_rad - other_lat_rad
dlng = lng_rad - other_lng_rad
a1 = math.sin(dlat / 2)**2
a2 = math.cos(lat_rad) * math.cos(other_lat_rad) * math.sin(dlng / 2)**2
return 2 * self._EARTH_RADIUS_METERS * math.asin(math.sqrt(a1 + a2))
def pitch(self):
return math.asin(2*(self.w*self.y() - self.z()*self.x()))
def get_distance(location1, location2):
lat1, lng1 = location1
lat2, lng2 = location2
lat1, lng1, lat2, lng2 = map(radians, (lat1, lng1, lat2, lng2))
d = sin(0.5*(lat2 - lat1)) ** 2 + cos(lat1) * cos(lat2) * sin(0.5*(lng2 - lng1)) ** 2
return 2 * earth_Rrect * asin(sqrt(d))
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
def ondraw(self):
# Calculate electric force
sk = self.sketch
dr = delta(self.pos, sk["blue"].pos)
r = hypot(*dr) / sk.scale / 100
F = delta(dr, mag = 8.99e-3 * sk.q1 * sk.q2 / (r * r))
# Add electric plus gravitational forces
F = F[0], F[1] + sk.mass * 9.81e-3
# Tangential acceleration
s = sk["string"]
u = s.u
t = 1 / sk.frameRate
F = (F[0] * u[1] - F[1] * u[0]) / (sk.mass / 1000) * (sk.scale / 100) / t ** 2
ax, ay = F * u[1], -F * u[0]
# Kinematics
v1x, v1y = tuple(0.95 * v for v in self.vel)
v2x = v1x + ax * t
v2y = v1y + ay * t
self.vel = v2x, v2y
x, y = self.pos
x += (v1x + v2x) * t / 2
y += (v1y + v2y) * t / 2
x, y = delta((x,y), s.pos, 20 * sk.scale)
self.pos = s.pos[0] + x, s.pos[1] + y
s.__init__(s.pos, self.pos)
# Protractor
if s.u[1] > 0:
a = round(2 * degrees(asin(s.u[0]))) / 2
a = "Angle = {:.1f}° ".format(abs(a))
else: a = "Angle = ? "
sk["angle"].config(data=a)
def checkFront(self):
"Update the front color sensor"
# Get sensor position
pos = delta(self.pos, vec2d(-self.radius, self.angle))
# Sensor distance to edge of sketch
sk = self.sketch
if sk.weight:
obj = sk
prox = _distToWall(pos, self.angle, self.sensorWidth, *sk.size)
else: obj = prox = None
# Find closest object within sensor width
u = vec2d(1, self.angle)
sw = self.sensorWidth * DEG
for gr in self.sensorObjects(sk):
if gr is not self and gr.avgColor and hasattr(gr, "rect"):
dr = delta(gr.rect.center, pos)
d = hypot(*dr)
r = gr.radius
if r >= d:
prox = 0
obj = gr
elif prox is None or d - r < prox:
minDot = cos(min(sw + asin(r/d), pi / 2))
x = (1 - sprod(u, dr) / d) / (1 - minDot)
if x < 1:
obj = gr
prox = (d - r) * (1 - x) + x * sqrt(d*d-r*r)
# Save data
self.closestObject = obj
c = rgba(sk.border if obj is sk
else obj.avgColor if obj else (0,0,0))
self.sensorFront = noise(divAlpha(c), self.sensorNoise, 255)
self.proximity = None if prox is None else round(prox)