Java、Scala使用tan和arctan求斜率和倾斜角

2021-04-27 14:33:45 浏览数 (1)

实现代码

代码语言:javascript复制
import java.text.DecimalFormat

object Test1 {

  def main(args: Array[String]): Unit = {

    val tan1 = getTanValue(0)    // tan(0°)=0
    val tan2 = getTanValue(45)   // tan(45°)=1
    val tan3 = getTanValue(90)   // tan(90°)=无限大(理论上不存在)
    val tan4 = getTanDegree(1)    // arctan(1)=45°
    val tan5 = getTanDegree(Int.MaxValue) // arctan(正无穷)=无限接近90°
  }

  /**
   * 已知tan角度,求斜率值
   * 求斜率:tan(45°)=1
   */
  def getTanValue(degree: Double): Double = {
    val value = new DecimalFormat("#.00").format(Math.tan(Math.toRadians(degree))).toDouble // tan(45°)=1
    println("tan("   degree   "°)="   value)
    value
  }

  /**
   * 已知斜率值,求斜率角
   * 求角度:arctan(1)=45°
   */
  def getTanDegree(value: Double): Double = {
    val degree = Math.toDegrees(Math.atan(value)) // arctan(1)=45°
    //    val degree = Math.atan(value)/Math.PI*180   // arctan(1)=45°
    println("arctan("   value   ")="   degree "°")
    value
  }

}

运行结果 

tan(0.0°)=0.0 tan(45.0°)=1.0 tan(90.0°)=1.633123935319537E16 arctan(1.0)=45.0° arctan(2.147483647E9)=89.99999997331958°

0 人点赞