You need to enable JavaScript to run this app. Python中如何将数值转换为弧度并实现三角函数对应换算
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将数值转换为弧度并实现三角函数对应换算

Python三角函数运算及数值匹配三角函数表达式实现方案

基础三角函数与弧度转换

Python 标准库自带的math模块已内置所有常用三角函数,模块内所有三角函数默认基于弧度计算,同时提供了角度与弧度的互转方法:

  • 角度转弧度:math.radians(角度值)
  • 弧度转角度:math.degrees(弧度值)
  • 基础三角函数:math.sin()、math.cos()、math.tan()
  • 反三角函数:math.asin()、math.acos()、math.atan()、math.atan2()(支持四象限识别)

基础使用示例:

import math

# 30度转弧度后计算sin值
rad_30 = math.radians(30)
print(math.sin(rad_30)) # 输出约0.49999999999999994,接近1/2

# π/6弧度转角度
deg_pi6 = math.degrees(math.pi/6)
print(deg_pi6) # 输出30.0

数值匹配三角函数表达式实现(如-1/2匹配为Sin(-π/6))

由于浮点数存在精度误差,我们设置容差阈值来匹配常见特殊角的三角函数值,示例函数如下:

import math

def match_trig_expression(value, tolerance=1e-9):
    # 预定义±2π范围内常用特殊角(弧度),可按需扩展
    special_angles = [
        -math.pi, -5*math.pi/6, -3*math.pi/4, -2*math.pi/3, -math.pi/2,
        -math.pi/3, -math.pi/4, -math.pi/6, 0,
        math.pi/6, math.pi/4, math.pi/3, math.pi/2,
        2*math.pi/3, 3*math.pi/4, 5*math.pi/6, math.pi
    ]
    # 弧度与可读表达式的映射表
    angle_str_map = {
        -math.pi: "-π", -5*math.pi/6: "-5π/6", -3*math.pi/4: "-3π/4", -2*math.pi/3: "-2π/3", -math.pi/2: "-π/2",
        -math.pi/3: "-π/3", -math.pi/4: "-π/4", -math.pi/6: "-π/6", 0: "0",
        math.pi/6: "π/6", math.pi/4: "π/4", math.pi/3: "π/3", math.pi/2: "π/2",
        2*math.pi/3: "2π/3", 3*math.pi/4: "3π/4", 5*math.pi/6: "5π/6", math.pi: "π"
    }
    # 优先级:sin > cos > tan,可按需调整顺序
    for angle in special_angles:
        if abs(math.sin(angle) - value) < tolerance:
            return f"Sin({angle_str_map[angle]})"
    for angle in special_angles:
        if abs(math.cos(angle) - value) < tolerance:
            return f"Cos({angle_str_map[angle]})"
    for angle in special_angles:
        if abs(math.tan(angle) - value) < tolerance:
            return f"Tan({angle_str_map[angle]})"
    # 未匹配到特殊角返回原值字符串
    return str(value)

# 测试用例
print(match_trig_expression(-1/2)) # 输出:Sin(-π/6)

如果需要覆盖更多特殊角,仅需要扩充special_angles和angle_str_map的对应条目即可。

内容的提问来源于stack exchange,提问作者Duy Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 23:39:02