感知面试手撕代码
* 给你三个点,怎么计算三个夹角的角度?
思路:用点积除叉积
python:
import numpy as np
def angle_between(v1, v2):
"""Returns the angle in radians between vectors 'v1' and 'v2'"""
cosang = np.dot(v1, v2)
sinang = np.linalg.norm(np.cross(v1, v2))
return np.arctan2(sinang, cosang)
def calculate_angle(p1, p2, p3):
"""Calculate the angle at p2"""
v1 = np.array(p1) - np.array(p2)
v2 = np.array(p3) - np.array(p2)
return angle_between(v1, v2)
p1 = [1, 0]
p2 = [0, 0]
p3 = [0, 1]
print(calculate_angle(p1, p2, p3))
C++
#include <cmath>
#include <iostream>
#include <vector>
struct Point {
double x, y, z;
};
double dot_product(Point a, Point b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
Point cross_product(Point a, Point b) {
return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
}
double norm(Point a) {
return std::sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}
double angle_between(Point a, Point b) {
double cosang = dot_product(a, b);
double sinang = norm(cross_product(a, b));
return std::atan2(sinang, cosang);
}
Point subtract(Point a, Point b) {
return {a.x - b.x, a.y - b.y, a.z - b.z};
}
double calculate_angle(Point p1, Point p2,