How to Find the Sin and Cos Value of a Number in Golang?


In mathematical calculations, trigonometric functions such as sine (sin) and cosine (cos) are commonly used. In Go programming language, you can find the sin and cos values of a number using the math package. In this article, we will discuss how to find the sin and cos values of a number in Golang.

Steps to Find the Sin and Cos Value of a Number in Golang

Import The Math Package

To use trigonometric functions in Go, you need to import the math package. You can do this by using the import statement −

import "math"

Define The Number

Define the number for which you want to find the sin and cos values. You can assign a value to a variable, or you can use a constant.

const x = 45.0 // degrees

Convert The Degrees to Radians

The trigonometric functions in Go use radians, not degrees. Therefore, you need to convert the degrees to radians using the math package. You can do this by multiplying the degrees by pi/180.

const pi = 3.14159265358979323846
y := x * pi / 180

Find The Sin and Cos Values

Use the math.Sin() and math.Cos() functions to find the sin and cos values of the number.

sinValue := math.Sin(y)
cosValue := math.Cos(y)

Print The Sin and Cos Values

Use the fmt.Println() function to print the sin and cos values of the number.

fmt.Printf("The sin value of %v is %v\n", x, sinValue)
fmt.Printf("The cos value of %v is %v\n", x, cosValue)

Example

package main

import (
   "fmt"
   "math"
)

func main() {
   const x = 45.0 // degrees
   const pi = 3.14159265358979323846
   y := x * pi / 180

   sinValue := math.Sin(y)
   cosValue := math.Cos(y)

   fmt.Printf("The sin value of %v is %v\n", x, sinValue)
   fmt.Printf("The cos value of %v is %v\n", x, cosValue)
}

Output

The sin value of 45 is 0.7071067811865475
The cos value of 45 is 0.7071067811865476

Conclusion

By using the math package in Go, you can easily find the sin and cos values of a number. Remember to convert degrees to radians before using trigonometric functions.

Updated on: 05-May-2023

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements