Skip to content

math: Sin(Pi) and Cos(Pi/2) should return 0 but don't #38039

@ijxy

Description

@ijxy

As the title says, the Sine and Cosine functions do not return zeros as expected.

Looking at the source, these values (which are surely special cases) are not checked in tests.

Could we add special cases to Sin and Cos (and Sincos) to return 0 identically at the required arguments, i.e. Sin(k*Pi) = Cos((2*k+1)*Pi/2) = 0, and add explicit tests for the first cases at least?

For example, a simple solution could be along the lines of:

func Sin(x float64) float64 {
	if r := x / math.Pi; r == float64(int(r)) {
		return 0
	}
        ...
}

func Cos(x float64) float64 {
	if r := x / (math.Pi / 2); r == float64(int(r)) {
		return 0
	}
	...
}

func Sincos(x float64) float64 {
	if r := x / math.Pi; r == float64(int(r)) {
                 // logic to determine whether Cos is + or -
		return 0, ±1
	}
	if r := x / (math.Pi / 2); r == float64(int(r)) {
                 // logic to determine whether Sin is + or -
		return ±1, 0
	}
        ...
}

What did you do?

https://play.golang.org/p/fqzS-dwzIFw

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions