我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.tan()。
def tHighDotOperator(stack, z, mode): if mode == 1: # num stack.append(utilities.formatNum(math.tan(z))) elif mode == 2: # str if z == "": stack.append("") else: stack.append(z + z[-2::-1]) elif mode == 3: # list if z == []: stack.append([]) else: stack.append(z + z[-2::-1]) else: monadNotImplemented(mode, '') # ?
def get_camera_params(box, size, view_angle): box_size = box.size() size_diagonal = math.hypot(*size) if view_angle is None: focal_length = size_diagonal # Normal lens by default else: focal_length = size_diagonal / (2 * math.tan(math.radians(view_angle) / 2)) distance = focal_length * max(_zero_if_inf(box_size.x) / size[0], _zero_if_inf(box_size.z) / size[1]) if distance == 0: distance = 1 distance *= 1.2 # 20% margin around the object origin = box.midpoint() - util.Vector(0, distance + _zero_if_inf(box_size.y) / 2, 0) direction = util.Vector(0, 1, 0) up = util.Vector(0, 0, 1) return (origin, direction, up, focal_length)
def construct_armature(name, bone_data_array): # bone_data =[boneIndex, boneName, parentIndex, parentName, bone_pos, optional ] print('[+] importing armature') bpy.ops.object.add( type='ARMATURE', enter_editmode=True, location=(0,0,0)) ob = bpy.context.object ob.show_x_ray = False ob.name = name amt = ob.data amt.name = name +'Amt' for bone_data in bone_data_array: bone = amt.edit_bones.new(bone_data[1]) bone.head = Vector(bone_data[4]) bone.tail = Vector(bone_data[4]) + Vector((0 , 0.01, 0)) bones = amt.edit_bones for bone_data in bone_data_array: if bone_data[2] < 0xffff: #this value need to edit in different games bone = bones[bone_data[1]] bone.parent = bones[bone_data[3]] bones[bone_data[3]].tail = bone.head bpy.ops.object.mode_set(mode='OBJECT') ob.rotation_euler = (math.tan(1),0,0) #split_armature(amt.name) #current not used return ob
def split_armature(name): amt = bpy.data.armatures[name] name = name.replace('Amt','') bones = amt.bones root_bones = [bone for bone in bones if not bone.parent] for i in range(len(root_bones)): bpy.ops.object.add( type='ARMATURE', enter_editmode=True, location=(i * 2,0,0)) ob_new = bpy.context.object ob_new.show_x_ray = False ob_new.name = "%s_%d" % (name, i) amt_new = ob_new.data amt_new.name = '%s_%d_Amt' % (name, i) copy_bone_tree(root_bones[i] ,amt_new) bpy.ops.object.mode_set(mode="OBJECT") ob_new.rotation_euler = (math.tan(1),0,0) bpy.ops.object.select_all(action="DESELECT") obj = bpy.data.objects[name] scene = bpy.context.scene scene.objects.unlink(obj) return False
def ellipsecomp(self, efactor, theta): if theta == self.a90: result = self.a90 elif theta == self.a180: result = self.a180 elif theta == self.a270: result = self.a270 elif theta == self.a360: result = 0.0 else: result = atan(tan(theta) / efactor ** 0.5) if result < 0.0: if theta > self.a180: result = result + self.a180 elif theta < self.a180: result = result + self.a180 if result > 0.0: if theta > self.a180: result = result + self.a180 elif theta < self.a180: result = result return result
def ellipsecomp(self, efactor, theta): if theta == self.a90: result = self.a90 elif theta == self.a270: result = self.a270 else: result = atan(tan(theta) / efactor**0.5) if result >= 0.0: x = result y = self.a180 + result if fabs(x - theta) <= fabs(y - theta): result = x else: result = y else: x = self.a180 + result y = result if fabs(x - theta) <= fabs(y - theta): result = x else: result = y return result
def rotateNormalizedCord(self, matx, maty, angle): h, w = matx.shape x_avg = np.mean(matx) x_min = np.min(matx) y_avg = np.mean(maty) y_min = np.min(maty) xmat = np.zeros((h, w), dtype=np.float) ymat = np.zeros((h, w), dtype=np.float) for k in range(h): for j in range(w): cor_y = k - h / 2 cor_x = j - w / 2 if cor_x == 0 and cor_y == 0: xmat[k][j] = x_avg ymat[k][j] = y_avg else: x_dis = math.cos(math.pi / 2 - angle) * (-math.tan(math.pi / 2 - angle) * cor_x + cor_y) xmat[k][j] = x_avg - (x_avg - x_min) * x_dis * 2 / w y_dis = math.cos(angle) * (math.tan(angle) * cor_x + cor_y) ymat[k][j] = y_avg + (y_avg - y_min) * y_dis * 2 / h return xmat, ymat
def BodyRatesToEarthRates(dcm, gyro): """Convert the angular velocities from body frame to earth frame. all inputs and outputs are in radians/s returns a earth rate vector. """ from math import sin, cos, tan, fabs p = gyro.x q = gyro.y r = gyro.z (phi, theta, psi) = dcm.to_euler() phiDot = p + tan(theta) * (q * sin(phi) + r * cos(phi)) thetaDot = q * cos(phi) - r * sin(phi) if fabs(cos(theta)) < 1.0e-20: theta += 1.0e-10 psiDot = (q * sin(phi) + r * cos(phi)) / cos(theta) return Vector3(phiDot, thetaDot, psiDot)
def test_vehicle_pipeline(self): throttle = random.uniform(-1.0, 1.0) angle = random.uniform(-1.0, 1.0) * config.car.max_steering_angle l_a = config.car.L w_d = config.car.W w_o = config.car.W_offset angle_radians = math.radians(angle) steer_tan = math.tan(angle_radians) r = l_a / steer_tan l_out = throttle * (1.0 - (w_d * 0.5 - w_o)/r ) * \ config.differential_car.left_mult r_out = throttle * (1.0 + (w_d * 0.5 + w_o)/r ) * \ config.differential_car.right_mult l_out = min(max(l_out, -1), 1) l_out = min(max(l_out, -1), 1) self.vehicle.pilot().set_response(angle, throttle) self.vehicle.step() self.assertAlmostEqual(self.vehicle.mixer.left_driver.output, l_out, places=5) self.assertAlmostEqual(self.vehicle.mixer.right_driver.output, r_out, places=5)
def skew_image(img, angle): """ Skew image using some math :param img: PIL image object :param angle: Angle in radians (function doesn't do well outside the range -1 -> 1, but still works) :return: PIL image object """ width, height = img.size # Get the width that is to be added to the image based on the angle of skew xshift = tan(abs(angle)) * height new_width = width + int(xshift) if new_width < 0: return img # Apply transform img = img.transform( (new_width, height), Image.AFFINE, (1, angle, -xshift if angle > 0 else 0, 0, 1, 0), Image.BICUBIC ) return img
def calc_curve(self,n=0,cpts_nr=20): #Anfangswerte fr Step und u u=0 step=float(self.Knots[-1])/(cpts_nr-1) Points=[] #Wenn die erste Ableitung oder hher errechnet wird die ersten #Ableitung in dem tan als Winkel in rad gespeichert tang=[] while u<=self.Knots[-1]: CK=self.bspline_ders_evaluate(n=n,u=u) #Den Punkt in einem Punkt List abspeichern Points.append(PointClass(x=CK[0][0],y=CK[0][1])) #Fr die erste Ableitung wird den Winkel der tangente errechnet if n>=1: tang.append(atan2(CK[1][1],CK[1][0])) u+=step return Points, tang #Modified Version of Algorithm A3.2 from "THE NURBS BOOK" pg.93
def _eq_of_time(self, juliancentury): epsilon = self._obliquity_correction(juliancentury) l0 = self._geom_mean_long_sun(juliancentury) e = self._eccentrilocation_earth_orbit(juliancentury) m = self._geom_mean_anomaly_sun(juliancentury) y = tan(radians(epsilon) / 2.0) y = y * y sin2l0 = sin(2.0 * radians(l0)) sinm = sin(radians(m)) cos2l0 = cos(2.0 * radians(l0)) sin4l0 = sin(4.0 * radians(l0)) sin2m = sin(2.0 * radians(m)) Etime = y * sin2l0 - 2.0 * e * sinm + 4.0 * e * y * sinm * cos2l0 - \ 0.5 * y * y * sin4l0 - 1.25 * e * e * sin2m return degrees(Etime) * 4.0
def getRadius(ra,dec): # M31 properties PA = 38.1 inclin = 77.5 centre = [10.77615,41.353394] # Center of our current FOV. #centre = [10.612508,41.208711] # Center from Viaene et al 2014 dist = 0.785 #Deproject the pixels to a physical radial distance. # convert angles to radians PA = ((90.-PA) / 180.0 * math.pi) inclin = inclin / 180.0 * math.pi radius = np.zeros(len(ra)) for i in range(0,len(ra)): Xsquare = ((ra[i] - centre[0])*math.cos(dec[i] / 180.0 * math.pi)*math.cos(PA) + (dec[i] - centre[1])*math.sin(PA))**2 Ysquare = (-(ra[i] - centre[0])*math.cos(dec[i] / 180.0 * math.pi)*math.sin(PA) + (dec[i] - centre[1])*math.cos(PA))**2 radius[i] = math.sqrt(Xsquare + Ysquare / math.cos(inclin)**2.0) radius[i] = 2.0 * dist * 1000.0 * math.tan(radius[i]*math.pi/(180.0*2.0)) return radius
def ackerman_model(x, u, L, dt): """Ackerman model Parameters ---------- x : u : L : dt : Returns ------- """ g1 = x[0] + u[0] * cos(x[2]) * dt g2 = x[1] + u[0] * sin(x[2]) * dt g3 = x[2] + ((u[0] * tan(x[2])) / L) * dt return np.array([g1, g2, g3])
def focal_length(image_width, image_height, fov): """Calculate focal length in the x and y axis from: - image width - image height - field of view Parameters ---------- image_width : int Image width image_height : int Image height fov : float Field of view Returns ------- (fx, fy) : (float, float) Focal length in x and y axis """ fx = (image_width / 2.0) / tan(deg2rad(fov) / 2.0) fy = (image_height / 2.0) / tan(deg2rad(fov) / 2.0) return (fx, fy)
def __ComputeCurved(vpercent, w, vec, via, pts, segs): """Compute the curves part points""" radius = via[1]/2.0 # Compute the bezier middle points req_angle = asin(vpercent/100.0) oppside = tan(req_angle)*(radius-(w/sin(req_angle))) length = sqrt(radius*radius + oppside*oppside) d = req_angle - acos(radius/length) vecBC = [vec[0]*cos(d)+vec[1]*sin(d), -vec[0]*sin(d)+vec[1]*cos(d)] pointBC = via[0] + wxPoint(int(vecBC[0] * length), int(vecBC[1] * length)) d = -d vecAE = [vec[0]*cos(d)+vec[1]*sin(d), -vec[0]*sin(d)+vec[1]*cos(d)] pointAE = via[0] + wxPoint(int(vecAE[0] * length), int(vecAE[1] * length)) curve1 = __Bezier(pts[1], pointBC, pts[2], n=segs) curve2 = __Bezier(pts[4], pointAE, pts[0], n=segs) return curve1 + [pts[3]] + curve2
def conferenceWakeOverlap(X, Y, R): n = np.size(X) # theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing for i in range(0, n): for j in range(0, n): if X[i] < X[j]: z = R/np.tan(0.34906585) # print z theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z)) # print 'theta =', theta if -0.34906585 < theta < 0.34906585: f_theta[i][j] = (1 + np.cos(9*theta))/2 # print f_theta # print z # print f_theta return f_theta
def conferenceWakeOverlap_tune(X, Y, R, boundAngle): n = np.size(X) boundAngle = boundAngle*np.pi/180.0 # theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing q = np.pi/boundAngle # factor inside the cos term of the smooth Jensen (see Jensen1983 eq.(3)) # print 'boundAngle = %s' %boundAngle, 'q = %s' %q for i in range(0, n): for j in range(0, n): if X[i] < X[j]: # z = R/tan(0.34906585) z = R/np.tan(boundAngle) # distance from fulcrum to wake producing turbine # print z theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z)) # print 'theta =', theta if -boundAngle < theta < boundAngle: f_theta[i][j] = (1. + np.cos(q*theta))/2. # print f_theta # print z # print f_theta return f_theta
def get_cosine_factor_original(X, Y, R0, bound_angle=20.0): n = np.size(X) bound_angle = bound_angle*np.pi/180.0 # theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing q = np.pi/bound_angle # factor inside the cos term of the smooth Jensen (see Jensen1983 eq.(3)) for i in range(0, n): for j in range(0, n): if X[i] < X[j]: z = R0/np.tan(bound_angle) # distance from fulcrum to wake producing turbine theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z)) if -bound_angle < theta < bound_angle: f_theta[i][j] = (1. + np.cos(q*theta))/2. return f_theta
def conferenceWakeOverlap_bk(X, Y, R): from math import atan, tan, cos n = np.size(X) # theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing for i in range(0, n): for j in range(0, n): if X[i] < X[j]: z = R/tan(0.34906585) theta = atan(Y[j] - Y[i]) / (X[j] - X[i] + z) if -0.34906585 < theta < 0.34906585: f_theta[i][j] = (1 + cos(9*theta))/2 # print f_theta return f_theta
def render(self, canvas): fovRadians = math.pi * (self.fieldOfView / 2.0) / 180.0 halfWidth = math.tan(fovRadians) halfHeight = 0.75 * halfWidth width = halfWidth * 2 height = halfHeight * 2 pixelWidth = width / (canvas.width - 1) pixelHeight = height / (canvas.height - 1) eye = Ray(self.position, self.lookingAt - self.position) vpRight = eye.vector.cross(Vector.UP).normalized() vpUp = vpRight.cross(eye.vector).normalized() for y in xrange(canvas.height): for x in xrange(canvas.width): xcomp = vpRight.scale(x * pixelWidth - halfWidth) ycomp = vpUp.scale(y * pixelHeight - halfHeight) ray = Ray(eye.point, eye.vector + xcomp + ycomp) colour = self.rayColour(ray) canvas.plot(x, y, *colour)
def centeroidPinHoleMode(height, focal, altitude, theta, yCoordinate): # height : jumlah baris (piksel) # focal -> |A'O| : focal length (piksel) # altitude -> |O'O| : tinggi kamera (m) # theta : sudut kemiringan kamera (derajat) # yCoordinate : indeks piksel Y object height = float(height) focal = float(focal) theta = float(theta) yCoordinate = float(yCoordinate) delta = math.degrees(math.atan(math.fabs(yCoordinate - (height / 2)) / focal)) if yCoordinate >= height / 2: lCentroid = altitude * math.tan(math.radians(theta + delta)) else: lCentroid = altitude * math.tan(math.radians(theta - delta)) lCentroid = round(lCentroid, 4) delta = round(delta, 4) # print "delta: {0} | lCentroid: {1}".format(delta, lCentroid) return lCentroid
def getCoordinateFromDistance(height, focal, altitude, theta, distance): # height : jumlah baris (piksel) # focal : panjang focal length kamera (piksel) # altitude : ketinggian kamera # theta : kemiringan kamera # distance : jarak yang ingin diketahui lokasinya distance = float(distance) altitude = float(altitude) focal = float(focal) alpha = math.degrees(math.atan(distance / altitude)) delta = theta - alpha yCoordinate = focal * math.tan(math.radians(delta)) yCoordinate += (height / 2) # print "alpha: {0} | delta: {1}".format(alpha, delta) return yCoordinate
def test_float_tan(self): i = '_float_tan' # 1 before = {'_float': [0.0]} after = {'_float': [0.0]} self.assertTrue(t_u.run_test(before, after, i)) # 2 before = {'_float': [1.0]} after = {'_float': [math.tan(1.0)]} self.assertTrue(t_u.run_test(before, after, i)) # 3 before = {'_float': [0.5]} after = {'_float': [math.tan(0.5)]} self.assertTrue(t_u.run_test(before, after, i)) # 4 before = {'_float': [-0.5]} after = {'_float': [math.tan(-0.5)]} self.assertTrue(t_u.run_test(before, after, i))
def IOR(self,n,k): theta_deg = 0 fresnel = [] while theta_deg <= 90: theta = math.radians(theta_deg) a = math.sqrt((math.sqrt((n**2-k**2-(math.sin(theta))**2)**2 + ((4 * n**2) * k**2)) + (n**2 - k**2 - (math.sin(theta))**2))/2) b = math.sqrt((math.sqrt((n**2-k**2-(math.sin(theta))**2)**2 + ((4 * n**2) * k**2)) - (n**2 - k**2 - (math.sin(theta))**2))/2) Fs = (a**2+b**2-(2 * a * math.cos(theta))+(math.cos(theta))**2)/(a**2+b**2+(2 * a * math.cos(theta))+(math.cos(theta))**2) Fp = Fs * ((a**2+b**2-(2 * a * math.sin(theta) * math.tan(theta))+(math.sin(theta))**2*(math.tan(theta))**2)/(a**2+b**2+(2 * a * math.sin(theta) * math.tan(theta))+(math.sin(theta))**2*(math.tan(theta))**2)) R = (Fs + Fp)/2 fresnel.append(R) theta_deg += 1 return fresnel
def change_prod_con(self, areas, prod, con, pf, tol=4, row=None, column=None): """Wrapper function to change load and production Args: areas: area number prod: production con: consumption pf: power factor tol: tolerance for round row: which row to write to column: which column to write to """ psspy.bsys(sid=0, numarea=1, areas=[areas]) psspy.scal_2(0, 0, 0, [0, 1, 1, 1, 0], [con, prod, 0.0, 0.0, 0.0, 0.0, round(con*math.tan(math.acos(pf)), tol)]) if self.to_excel: self.sheet.cell(row=row, column=column).value = prod self.sheet.cell(row=row, column=column+1).value = con
def execute(self,obj): import Part,FreeCAD l2=obj.S.Value/2. q=2*l2*tan(radians(22.5)) v1 = FreeCAD.Base.Vector(l2,-l2,-l2) v2 = FreeCAD.Base.Vector(l2,-l2,l2) v3 = FreeCAD.Base.Vector(-l2,-l2,l2+q) v4 = FreeCAD.Base.Vector(-l2-q,-l2,l2) v5 = FreeCAD.Base.Vector(-l2,-l2,-l2) l1= Part.makePolygon([v1,v2,v3,v4,v5,v1]) F = Part.Face(Part.Wire(l1.Edges)) d = F.extrude(FreeCAD.Base.Vector(0,2*l2,0)) obj.Shape = d
def execute(self,obj): import Part,FreeCAD dist = obj.distribution.lower() if dist not in ["polar","cartesian"]: obj.distribution="polar" print "Ray Distribution not understood, changing it to polar" if dist == "polar": print obj.angle , type(obj.angle) r=5*tan(obj.angle.getValueAs("rad").Value) d=Part.makeCone(0,r,5) #d.translate(FreeCAD.Base.Vector(0,0,-0.5)) else: #Cartesian #Todo: Change to piramis instead of a cone r=5*tan(obj.angle.getValueAs("rad").Value) d=Part.makeCone(0,r,5) obj.Shape = d
def execute(self,obj): import Part,FreeCAD dist = obj.distribution.lower() if dist not in ["polar","cartesian"]: obj.distribution="polar" print "Ray Distribution not understood, changing it to polar" if dist == "polar": r=5*tan(radians(obj.angle)) d=[] for x in linspace(-obj.xSize/2,obj.xSize/2,obj.Nx): for y in linspace(-obj.ySize/2,obj.ySize/2,obj.Ny): d.append(Part.makeCone(0,r,5,FreeCAD.Vector(x,y,0))) else: #Todo: Cambiar cono a piramide r=5*tan(radians(obj.angle)) d = [] for x in linspace(-obj.xSize/2,obj.xSize/2,obj.Nx): for y in linspace(-obj.ySize/2,obj.ySize/2,obj.Ny): d.append(Part.makeCone(0,r,5,FreeCAD.Vector(x,y,0))) obj.Shape = Part.makeCompound(d)
def sample_transformation(self, imsz): theta = math.radians(self.rotation[1]*n.random.randn() + self.rotation[0]) ca = math.cos(theta) sa = math.sin(theta) R = n.zeros((3,3)) R[0,0] = ca R[0,1] = -sa R[1,0] = sa R[1,1] = ca R[2,2] = 1 S = n.eye(3,3) S[0,1] = math.tan(math.radians(self.skew[1]*n.random.randn() + self.skew[0])) A = matrix_mult(R,S) x = imsz[1]/2 y = imsz[0]/2 return (A[0,0], A[0,1], -x*A[0,0] - y*A[0,1] + x, A[1,0], A[1,1], -x*A[1,0] - y*A[1,1] + y)
def calculate_camera_variables(eye, lookat, up, fov, aspect_ratio, fov_is_vertical=False): import numpy as np import math W = np.array(lookat) - np.array(eye) wlen = np.linalg.norm(W) U = np.cross(W, np.array(up)) U /= np.linalg.norm(U) V = np.cross(U, W) V /= np.linalg.norm(V) if fov_is_vertical: vlen = wlen * math.tan(0.5 * fov * math.pi / 180.0) V *= vlen ulen = vlen * aspect_ratio U *= ulen else: ulen = wlen * math.tan(0.5 * fov * math.pi / 180.0) U *= ulen vlen = ulen * aspect_ratio V *= vlen return U, V, W
def nh_steer(self, q_nearest, q_rand, epsilon): """ For a car like robot, where it takes two control input (u_speed, u_phi) All possible combinations of control inputs are generated and used to find the closest q_new to q_rand :param q_nearest: :param q_rand: :param epsilon: :return: """ L = 20.0 # Length between midpoints of front and rear axle of the car like robot u_speed, u_phi = [-1.0, 1.0], [-math.pi/4, 0, math.pi/4] controls = list(itertools.product(u_speed, u_phi)) # euler = lambda t_i, q, u_s, u_p, L: (u_s*math.cos(q[2]), u_s*math.sin(q[2]), u_s/L*math.tan(u_p)) result = [] ctrls_path = {c: [] for c in controls} for ctrl in controls: q_new = q_nearest for t_i in range(epsilon): # h is assumed to be 1 here for euler integration q_new = tuple(map(add, q_new, self.euler(t_i, q_new, ctrl[0], ctrl[1], L))) ctrls_path[ctrl].append(q_new) result.append((ctrl[0], ctrl[1], q_new)) q_news = [x[2] for x in result] _, _, idx = self.nearest_neighbour(q_rand, np.array(q_news)) return result[idx], ctrls_path
def process(self, im): # if side is right flip so it becomes right if self.side != 'left': im = np.fliplr(im) # slope of the perspective slope = tan(radians(self.degrees)) (h, w, _) = im.shape matrix_trans = np.array([[1, 0, 0], [-slope/2, 1, slope * h / 2], [-slope/w, 0, 1 + slope]]) trans = ProjectiveTransform(matrix_trans) img_trans = warp(im, trans) if self.side != 'left': img_trans = np.fliplr(img_trans) return img_trans
def angled_path(size, angle=0): """ Generates a set of lines across an image, with the given angle. :param size: The size of the image :param angle: The angle of the lines. :return: A set of generators, each generator represents a line and yields a set of (x,y) coordinates. All the lines go left to right. """ # y coordinates are inverted in images, so this allows for users to input more intuitive angle values. angle = -angle if angle % 180 == 0: yield from horizontal_path(size) return if angle % 180 == 90: yield from vertical_path(size) return width, height = size slope = tan(radians(angle)) start_y = 0 if slope > 0 else height - 1 for x in range(width-1, 0, -1): yield draw_line((x, start_y), size, slope) for y in range(height): yield draw_line((0, y), size, slope)
def calc_helix_points(turtle, rad, pitch): """ calculates required points to produce helix bezier curve with given radius and pitch in direction of turtle""" # alpha = radians(90) # pit = pitch/(2*pi) # a_x = rad*cos(alpha) # a_y = rad*sin(alpha) # a = pit*alpha*(rad - a_x)*(3*rad - a_x)/(a_y*(4*rad - a_x)*tan(alpha)) # b_0 = Vector([a_x, -a_y, -alpha*pit]) # b_1 = Vector([(4*rad - a_x)/3, -(rad - a_x)*(3*rad - a_x)/(3*a_y), -a]) # b_2 = Vector([(4*rad - a_x)/3, (rad - a_x)*(3*rad - a_x)/(3*a_y), a]) # b_3 = Vector([a_x, a_y, alpha*pit]) # axis = Vector([0, 0, 1]) # simplifies greatly for case inc_angle = 90 points = [Vector([0, -rad, -pitch / 4]), Vector([(4 * rad) / 3, -rad, 0]), Vector([(4 * rad) / 3, rad, 0]), Vector([0, rad, pitch / 4])] # align helix points to turtle direction and randomize rotation around axis trf = turtle.dir.to_track_quat('Z', 'Y') spin_ang = rand_in_range(0, 2 * pi) for p in points: p.rotate(Quaternion(Vector([0, 0, 1]), spin_ang)) p.rotate(trf) return points[1] - points[0], points[2] - points[0], points[3] - points[0], turtle.dir.copy()
def update_projection_matrix(self): u = self.z_near*tan(radians(self.fov)) r = u*self.width()/self.height() self.projection_matrix = create_frustum_matrix(-r,r,-u,u,self.z_near,self.z_far) self.projection_matrix_need_update = False
def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transformed by the shear matrix into P" such that the vector P-P" is parallel to the direction vector and its extent is given by the angle of P-P'-P", where P' is the orthogonal projection of P onto the shear plane. >>> angle = (random.random() - 0.5) * 4*math.pi >>> direct = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.cross(direct, numpy.random.random(3)) >>> S = shear_matrix(angle, direct, point, normal) >>> numpy.allclose(1.0, numpy.linalg.det(S)) True """ normal = unit_vector(normal[:3]) direction = unit_vector(direction[:3]) if abs(numpy.dot(normal, direction)) > 1e-6: raise ValueError("direction and normal vectors are not orthogonal") angle = math.tan(angle) M = numpy.identity(4) M[:3, :3] += angle * numpy.outer(direction, normal) M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction return M
def skew(self, x=0, y=0): """Return a new transformation, skewed by x and y. Example: >>> import math >>> t = Transform() >>> t.skew(math.pi / 4) <Transform [1 0 1 1 0 0]> >>> """ import math return self.transform((1, math.tan(y), math.tan(x), 1, 0, 0))
def findDistance(TP): #this function finds the distance from the reflector FIX FPw = img.shape[1] FMw = TMw * FPw / TP[1] #print FMw, TMw, FPw, TP[1] distw = (FMw / 2) * math.tan(math.radians(TAN_ANGLE_HORI)) FPh = img.shape[0] FMh = TMh * FPh / TP[0] #print FMh, TMh, FPh, TP#[0] disth = (FMh / 2) * math.tan(math.radians(TAN_ANGLE_VERT)) dist = (distw + disth) #dist = disth * 8 return dist
def findDistance(TP): """ this function finds the distance from the reflector FIX """ FPw = img.shape[1] FMw = TMw * FPw / TP[1] distw = (FMw / 2) * math.tan(math.radians(TAN_ANGLE_HORI)) FPh = img.shape[0] FMh = TMh * FPh / TP[0] disth = (FMh / 2) * math.tan(math.radians(TAN_ANGLE_VERT)) dist = (distw + disth) return dist
def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transformed by the shear matrix into P" such that the vector P-P" is parallel to the direction vector and its extent is given by the angle of P-P'-P", where P' is the orthogonal projection of P onto the shear plane. >>> angle = (random.random() - 0.5) * 4*math.pi >>> direct = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.cross(direct, numpy.random.random(3)) >>> S = shear_matrix(angle, direct, point, normal) >>> numpy.allclose(1, numpy.linalg.det(S)) True """ normal = unit_vector(normal[:3]) direction = unit_vector(direction[:3]) if abs(numpy.dot(normal, direction)) > 1e-6: raise ValueError("direction and normal vectors are not orthogonal") angle = math.tan(angle) M = numpy.identity(4) M[:3, :3] += angle * numpy.outer(direction, normal) M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction return M
def st_to_uv(cls, s): if cls.PROJECTION == cls.LINEAR_PROJECTION: return 2 * s - 1 elif cls.PROJECTION == cls.TAN_PROJECTION: s = math.tan((math.pi / 2.0) * s - math.pi / 4.0) return s + (1.0 / (1 << 53)) * s elif cls.PROJECTION == cls.QUADRATIC_PROJECTION: if s >= 0.5: return (1.0 / 3.0) * (4 * s * s - 1) else: return (1.0 / 3.0) * (1 - 4 * (1 - s) * (1 - s)) else: raise ValueError('unknown projection type')
def area(a, b, c): """Area of the triangle (a, b, c). see :cpp:func:`S2::Area` """ assert is_unit_length(a) assert is_unit_length(b) assert is_unit_length(c) sa = b.angle(c) sb = c.angle(a) sc = a.angle(b) s = 0.5 * (sa + sb + sc) if s >= 3e-4: s2 = s * s dmin = s - max(sa, max(sb, sc)) if dmin < 1e-2 * s * s2 * s2: area = girard_area(a, b, c) if dmin < 2 * (0.1 * area): return area return 4 * math.atan(math.sqrt( max(0.0, math.tan(0.5 * s) * math.tan(0.5 * (s - sa)) * math.tan(0.5 * (s - sb)) * math.tan(0.5 * (s - sc))) ))
def __calc(self): """ Perform the actual calculations for sunrise, sunset and a number of related quantities. The results are stored in the instance variables sunrise_t, sunset_t and solarnoon_t """ timezone = self.timezone # in hours, east is positive longitude= self.long # in decimal degrees, east is positive latitude = self.lat # in decimal degrees, north is positive time = self.time # percentage past midnight, i.e. noon is 0.5 day = self.day # daynumber 1=1/1/1900 Jday =day+2415018.5+time-timezone/24 # Julian day Jcent =(Jday-2451545)/36525 # Julian century Manom = 357.52911+Jcent*(35999.05029-0.0001537*Jcent) Mlong = 280.46646+Jcent*(36000.76983+Jcent*0.0003032)%360 Eccent = 0.016708634-Jcent*(0.000042037+0.0001537*Jcent) Mobliq = 23+(26+((21.448-Jcent*(46.815+Jcent*(0.00059-Jcent*0.001813))))/60)/60 obliq = Mobliq+0.00256*cos(rad(125.04-1934.136*Jcent)) vary = tan(rad(obliq/2))*tan(rad(obliq/2)) Seqcent = sin(rad(Manom))*(1.914602-Jcent*(0.004817+0.000014*Jcent))+sin(rad(2*Manom))*(0.019993-0.000101*Jcent)+sin(rad(3*Manom))*0.000289 Struelong= Mlong+Seqcent Sapplong = Struelong-0.00569-0.00478*sin(rad(125.04-1934.136*Jcent)) declination = deg(asin(sin(rad(obliq))*sin(rad(Sapplong)))) eqtime = 4*deg(vary*sin(2*rad(Mlong))-2*Eccent*sin(rad(Manom))+4*Eccent*vary*sin(rad(Manom))*cos(2*rad(Mlong))-0.5*vary*vary*sin(4*rad(Mlong))-1.25*Eccent*Eccent*sin(2*rad(Manom))) hourangle= deg(acos(cos(rad(90.833))/(cos(rad(latitude))*cos(rad(declination)))-tan(rad(latitude))*tan(rad(declination)))) self.solarnoon_t=(720-4*longitude-eqtime+timezone*60)/1440 self.sunrise_t =self.solarnoon_t-hourangle*4/1440 self.sunset_t =self.solarnoon_t+hourangle*4/1440
def __init__(self, root, tip, span, sweep=None, sweepangle=45.0): self.root = root #: Root Chord of fin self.tip = tip #: Tip Chord of fin self.span = span #: Span ("height") of fin self._length = root if sweep is not None: self.sweep = sweep #: Sweep length of the fin self.sweepangle = atan(self.sweep / self.span) """Angle of sweep of the fin [radians]""" else: self.sweep = span * tan(radians(sweepangle)) self.sweepangle = radians(sweepangle)
def target_distance(target): camera_fov_vert = 41.41 camera_pitch = 40 # units in inches target_height = 83 camera_height = 9 # target[0][1] is [1,-1] y coord from top-bottom y = target[0][1] return (target_height - camera_height) / math.tan(math.radians((y * camera_fov_vert / 2) + camera_pitch))
def destinationPointVincenty(lat, lon, brng, s): a = 6378137.0 b = 6356752.3142 f = 1.0/298.257223563 alpha1 = math.radians(brng) sinAlpha1 = math.sin(alpha1) cosAlpha1 = math.cos(alpha1) tanU1 = (1.0 - f) * math.tan(math.radians(lat)) cosU1 = 1.0 / math.sqrt(1.0 + tanU1*tanU1) sinU1 = tanU1 * cosU1 sigma1 = math.atan2(tanU1, cosAlpha1) sinAlpha = cosU1 * sinAlpha1 cosSqAlpha = 1.0 - sinAlpha*sinAlpha uSq = cosSqAlpha * (a*a - b*b) / (b*b) A = 1.0 + uSq / 16384.0 * (4096.0+uSq*(-768.0+uSq*(320.0-175.0*uSq))) B = uSq / 1024.0 * (256.0+uSq*(-128.0+uSq*(74.0-47.0*uSq))) sigma = s / (b*A) sigmaP = 2.0 * math.pi while math.fabs(sigma-sigmaP) > 1e-12: cos2SigmaM = math.cos(2.0 * sigma1 + sigma) sinSigma = math.sin(sigma) cosSigma = math.cos(sigma) deltaSigma = B * sinSigma * (cos2SigmaM+B/4.0*(cosSigma*(-1.0+2.0*cos2SigmaM*cos2SigmaM) - B/6.0*cos2SigmaM*(-3.0+4.0*sinSigma*sinSigma)*(-3.0+4.0*cos2SigmaM*cos2SigmaM))) sigmaP = sigma sigma = s / (b*A) + deltaSigma tmp = sinU1 * sinSigma - cosU1*cosSigma*cosAlpha1 lat2 = math.atan2(sinU1*cosSigma + cosU1*sinSigma*cosAlpha1, (1.0 - f)*math.sqrt(sinAlpha*sinAlpha + tmp*tmp)) lambdav = math.atan2(sinSigma*sinAlpha1, cosU1*cosSigma - sinU1*sinSigma*cosAlpha1) C = f / 16.0 * cosSqAlpha*(4.0+f*(4.0-3.0*cosSqAlpha)) L = lambdav - (1.0-C) * f * sinAlpha * (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1.0+2.0*cos2SigmaM*cos2SigmaM))) return math.degrees(lat2), lon + math.degrees(L) # bearing is in degrees and distances are in meters