Taskintro
Use mathematical constants and functions
Also called math library, math functions, pi constant, Math.PI, math.pi, square root, power function, trigonometric functions, degrees to radians, natural logarithm, real constants and functions.
Use pi, e, the square root, the power, the trigonometric functions and the logarithms of the math library, here to turn a distance and an angle in degrees into x and y coordinates.
- Evidence
- Code in 10 languages
Task
Use the constants and functions of the math library of the language: pi, e, the square root, the power, the trigonometric functions and the logarithms. The Rosetta Code task on real constants and functions asks for e, pi, the square root, the logarithm, the exponential, the absolute value, the floor, the ceiling and the power1.
The contract uses pi and the trigonometric functions. The function to_cartesian(r, degrees) takes a distance r and an angle in degrees, measured from the positive x axis in the counterclockwise direction. It returns the point (x, y), with x = r cos(t) and y = r sin(t), where t is the angle in radians. For example, to_cartesian(2, 90) is (0, 2), and to_cartesian(1, 45) is about (0.7071, 0.7071).
The trigonometric functions of each library take radians. A full turn is 360 degrees or 2 pi radians, so the conversion is t = degrees * pi / 180.
The results are floating-point numbers, and they are not exact. cos(90 degrees) gives about 6.1e-17, not 0. So the checker of the contract compares the numbers with an absolute tolerance of 1e-9 or a relative tolerance of 1e-12.
Solutions
| Language | pi | e | Square root | Power | Sine of an angle in degrees | Natural logarithm |
|---|---|---|---|---|---|---|
| Python | math.pi |
math.e |
math.sqrt(x) |
x ** y |
math.sin(math.radians(d)) |
math.log(x) |
| JavaScript, TypeScript | Math.PI |
Math.E |
Math.sqrt(x) |
x ** y |
Math.sin(d * Math.PI / 180) |
Math.log(x) |
| Java | Math.PI |
Math.E |
Math.sqrt(x) |
Math.pow(x, y) |
Math.sin(Math.toRadians(d)) |
Math.log(x) |
| C# | Math.PI |
Math.E |
Math.Sqrt(x) |
Math.Pow(x, y) |
Math.Sin(d * Math.PI / 180) |
Math.Log(x) |
| Go | math.Pi |
math.E |
math.Sqrt(x) |
math.Pow(x, y) |
math.Sin(d * math.Pi / 180) |
math.Log(x) |
| Rust | std::f64::consts::PI |
std::f64::consts::E |
x.sqrt() |
x.powf(y) |
d.to_radians().sin() |
x.ln() |
| C | acos(-1.0) |
exp(1.0) |
sqrt(x) |
pow(x, y) |
sin(d * pi / 180) |
log(x) |
| C++ | std::numbers::pi |
std::numbers::e |
std::sqrt(x) |
std::pow(x, y) |
std::sin(d * pi / 180) |
std::log(x) |
| Bash | atan2(0, -1) in awk |
exp(1) in awk |
sqrt(x) in awk |
x ^ y in awk |
sin(d * pi / 180) in awk |
log(x) in awk |
- Python. The
mathmodule has the constantsmath.pi,math.e,math.tau,math.infandmath.nan.math.piis "The mathematical constant π = 3.141592…, to available precision"2.math.radians(x)andmath.degrees(x)convert the angles.math.log(x, base)takes a base, andmath.log2andmath.log10are more exact for the bases 2 and 10. - JavaScript.
Mathis an object with static properties and methods: "Unlike most global objects, Math is not a constructor"3. "Math works with the Number type. It doesn't work with BigInt"3. There is no function for degrees, so the solution multiplies byMath.PI / 180. - TypeScript. The same code as JavaScript, with the type
[number, number]for the result. - Java.
Math.toRadians"Converts an angle measured in degrees to an approximately equivalent angle measured in radians. The conversion from degrees to radians is generally inexact"4. - C#.
Math.PI"Represents the ratio of the circumference of a circle to its diameter, specified by the constant, π"5.Math.Log(Double)"Returns the natural (base e) logarithm of a specified number"5, andMath.Log(Double, Double)takes a base. The solution returns the tuple(double X, double Y). - Go. The constants of the
mathpackage are untyped constants with more digits than afloat64holds:Pi = 3.141592653589793238462643383279502884197169399375105820974944596. The function returns two values. - Rust. The constants are in
std::f64::consts, wherePIis "Archimedes' constant (π)"7. The functions are methods off64, sod.to_radians().sin()reads from left to right.to_radians"Converts degrees to radians"8. - C. The C standard library has no constant for pi. POSIX defines
M_PIin<math.h>as the value of pi9, but a compiler in strict standard mode can hide it. The solution computes pi asacos(-1.0). On some systems the math functions need the option-lmat link time. - C++. The header
<numbers>hasstd::numbers::pi, adoubleconstant, and the templatestd::numbers::pi_v<T>for other types10. - Bash. "Evaluation is done in the largest fixed-width integers available"11, so Bash has no floating-point numbers. The solution calls awk, which has the arithmetic functions
atan2(y,x),cos(x),sin(x),exp(x),log(x)andsqrt(x), andcos(x)returns the "cosine of x, where x is in radians"12. It prints the coordinates with 6 decimals.
A table of the functions and constants in Python:
import math
print(math.pi, math.e)
print(math.sqrt(2), 2 ** 0.5)
print(math.exp(1), math.log(math.e), math.log10(1000), math.log(8, 2))
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), abs(-2.5))
print(math.sin(math.radians(30)), math.degrees(math.pi))
print(math.hypot(3, 4), math.atan2(1, 1) * 4)
3.141592653589793 2.718281828459045
1.4142135623730951 1.4142135623730951
2.718281828459045 1.0 3.0 3.0
-3 -2 -2 2.5
0.49999999999999994 180.0
5.0 3.141592653589793
The sine of 30 degrees is 0.5, but the result is 0.49999999999999994, because math.radians(30) is not exactly pi / 6. The floor of -2.5 is -3, and the truncation is -2.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
east,northandwest: the angles 0, 90 and 180 degrees. The result ofnorthhas an x of about 6.1e-17, not 0, and the tolerance of the checker accepts it.diagonalandthirty-degrees: the results are irrational numbers, so they are not exact.zero-radius: a distance of 0 gives the origin for each angle.southandnegative-angle: 270 degrees and -90 degrees give the same point.full-turnandtwo-turns: 360 and 720 degrees give the same point as 0 degrees.negative-radius: a negative distance gives the point on the other side of the origin.large-radius: the relative tolerance accepts the error in the last digits of large results.
Pitfalls
- The trigonometric functions take radians. A call with an angle in degrees gives a wrong result and no error.
math.sin(90)is the sine of 90 radians:
This code runs but gives a wrong answer on purpose.
import math
print(math.sin(90))
print(math.sin(math.radians(90)))
0.8939966636005579
1.0
- A result that should be 0 is a small number. pi is not exact in a
float, socos(pi / 2)is not 0. Do not compare floating-point results with==. Compare them with a tolerance, such asmath.isclose. For a comparison with 0, give an absolute tolerance, because "isclose(x, 0) is computed as abs(x) <= rel_tol * abs(x), which is False for any nonzero x"2:
import math
x = math.cos(math.pi / 2)
print(x)
print(x == 0, math.isclose(x, 0), math.isclose(x, 0, abs_tol=1e-9))
6.123233995736766e-17
False False True
^is not the power operator. In C, C++, Java, C#, Go, Rust and JavaScript,^is the bitwise exclusive or. In JavaScript, it "returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either but not both operands are 1"13. So2 ^ 3is 1. Use**in Python and JavaScript, and the power function in the other languages:
This code runs but gives a wrong answer on purpose.
console.log(2 ^ 3);
console.log(2 ** 3, Math.pow(2, 3));
1
8 8
- A floating-point power of integers loses digits.
math.powandpowin C, Java, C# and Go convert the arguments todouble, which holds 53 bits. Python says: "Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers"2. 3 to the power 39 needs 62 bits, so thefloatresult is wrong in the last digits:
This code runs but gives a wrong answer on purpose.
import math
print(3 ** 39)
print(int(math.pow(3, 39)))
4052555153018976267
4052555153018976256
The same is true in Go, where math.Pow returns a float64:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"math"
)
func main() {
exact := int64(1)
for range 39 {
exact *= 3
}
fmt.Println(exact)
fmt.Println(int64(math.Pow(3, 39)))
}
4052555153018976267
4052555153018976256
- A value outside the domain gives an error or NaN. The logarithm of 0 or of a negative number, and the square root of a negative number, have no real result. Python raises an error: "The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0)"2. Go returns special values: "Log(0) = -Inf", "Log(x < 0) = NaN" and "Sqrt(x < 0) = NaN"6. Check the argument first, or check the result with
math.IsNaNandmath.IsInf:
import math
for f, x in [(math.log, 0.0), (math.sqrt, -1.0)]:
try:
f(x)
except ValueError as e:
print(f.__name__, type(e).__name__)
log ValueError
sqrt ValueError
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Log(0), math.Log(-1), math.Sqrt(-1))
fmt.Println(math.IsNaN(math.Sqrt(-1)), math.IsInf(math.Log(0), -1))
}
-Inf NaN NaN
true true
- Integer arguments in C. In C,
sqrt(2)converts the 2 todouble, but1 / 2 * piis 0, because1 / 2is an integer division. Write the constants as1.0 / 2. See Integer division and modulo.
Related tasks
- Sum and multiply a list: the sum and the product of many numbers.
- Compute the mean and median: the mean needs a floating-point division.
- Do complex number arithmetic: the absolute value and the phase of a complex number use the square root and
atan2. - Generate random numbers: random numbers are the other part of the math library.
See Numeric type for the types of numbers, and Numerical pitfalls for the errors of floating-point arithmetic.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
import math
def to_cartesian(r: float, degrees: float) -> tuple[float, float]:
"""Return the point (x, y) at the distance r and the angle in degrees."""
t = math.radians(degrees)
return r * math.cos(t), r * math.sin(t)
test_cartesian.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
import math
import pytest
from cartesian import to_cartesian
CASES = [
("east", 1.0, 0.0, (1.0, 0.0)),
("north", 2.0, 90.0, (0.0, 2.0)),
("west", 2.0, 180.0, (-2.0, 0.0)),
("diagonal", 1.0, 45.0, (0.7071067811865476, 0.7071067811865476)),
("thirty-degrees", 2.0, 30.0, (1.7320508075688772, 1.0)),
("zero-radius", 0.0, 123.0, (0.0, 0.0)),
("south", 1.0, 270.0, (0.0, -1.0)),
("negative-angle", 1.0, -90.0, (0.0, -1.0)),
("full-turn", 1.0, 360.0, (1.0, 0.0)),
("two-turns", 3.0, 720.0, (3.0, 0.0)),
("negative-radius", -1.0, 0.0, (-1.0, 0.0)),
("large-radius", 1000000.0, 60.0, (500000.0, 866025.4037844386)),
]
def close(got, want):
return math.isclose(got, want, rel_tol=1e-12, abs_tol=1e-9)
@pytest.mark.parametrize(("name", "r", "degrees", "want"), CASES, ids=[c[0] for c in CASES])
def test_to_cartesian(name, r, degrees, want):
x, y = to_cartesian(r, degrees)
assert close(x, want[0]) and close(y, want[1])
def test_constants():
assert math.isclose(math.atan2(0, -1), math.pi)
assert math.isclose(math.log(math.e), 1)
assert math.sqrt(16) == 4
assert 2**10 == 1024
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
#ifndef TO_CARTESIAN_HPP
#define TO_CARTESIAN_HPP
#include <cmath>
#include <numbers>
#include <utility>
// Returns the point (x, y) at the distance r and the angle in degrees.
inline std::pair<double, double> to_cartesian(double r, double degrees) {
const double t = degrees * std::numbers::pi / 180.0;
return {r * std::cos(t), r * std::sin(t)};
}
#endif
test_cartesian.cpp 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include "cartesian.hpp"
namespace {
struct test_case {
const char* name;
double r, degrees, x, y;
};
const test_case cases[] = {
{"east", 1.0, 0.0, 1.0, 0.0},
{"north", 2.0, 90.0, 0.0, 2.0},
{"west", 2.0, 180.0, -2.0, 0.0},
{"diagonal", 1.0, 45.0, 0.7071067811865476, 0.7071067811865476},
{"thirty-degrees", 2.0, 30.0, 1.7320508075688772, 1.0},
{"zero-radius", 0.0, 123.0, 0.0, 0.0},
{"south", 1.0, 270.0, 0.0, -1.0},
{"negative-angle", 1.0, -90.0, 0.0, -1.0},
{"full-turn", 1.0, 360.0, 1.0, 0.0},
{"two-turns", 3.0, 720.0, 3.0, 0.0},
{"negative-radius", -1.0, 0.0, -1.0, 0.0},
{"large-radius", 1000000.0, 60.0, 500000.0, 866025.4037844386},
};
bool close_to(double got, double want) {
return std::abs(got - want) <= std::max(1e-9, 1e-12 * std::abs(want));
}
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const auto [x, y] = to_cartesian(c.r, c.degrees);
if (!close_to(x, c.x) || !close_to(y, c.y)) {
std::printf("FAIL %s: (%.17g, %.17g)\n", c.name, x, y);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
/** Turns a distance and an angle in degrees into the coordinates x and y. */
public final class Cartesian {
private Cartesian() {}
/** Returns {x, y} at the distance r and the angle in degrees. */
public static double[] toCartesian(double r, double degrees) {
double t = Math.toRadians(degrees);
return new double[] {r * Math.cos(t), r * Math.sin(t)};
}
}
CartesianTest.java 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class CartesianTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("east", 1.0, 0.0, 1.0, 0.0),
Arguments.of("north", 2.0, 90.0, 0.0, 2.0),
Arguments.of("west", 2.0, 180.0, -2.0, 0.0),
Arguments.of("diagonal", 1.0, 45.0, 0.7071067811865476, 0.7071067811865476),
Arguments.of("thirty-degrees", 2.0, 30.0, 1.7320508075688772, 1.0),
Arguments.of("zero-radius", 0.0, 123.0, 0.0, 0.0),
Arguments.of("south", 1.0, 270.0, 0.0, -1.0),
Arguments.of("negative-angle", 1.0, -90.0, 0.0, -1.0),
Arguments.of("full-turn", 1.0, 360.0, 1.0, 0.0),
Arguments.of("two-turns", 3.0, 720.0, 3.0, 0.0),
Arguments.of("negative-radius", -1.0, 0.0, -1.0, 0.0),
Arguments.of("large-radius", 1000000.0, 60.0, 500000.0, 866025.4037844386)
);
}
static boolean close(double got, double want) {
return Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void toCartesian(String name, double r, double degrees, double wantX, double wantY) {
double[] p = Cartesian.toCartesian(r, degrees);
assertTrue(close(p[0], wantX), "x = " + p[0]);
assertTrue(close(p[1], wantY), "y = " + p[1]);
}
@Test
void constants() {
assertTrue(close(Math.atan2(0, -1), Math.PI));
assertEquals(4.0, Math.sqrt(16));
assertEquals(1024.0, Math.pow(2, 10));
assertEquals(8, 2 ^ 10);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
#include "cartesian.h"
#include <math.h>
// Standard C has no constant for pi; M_PI is POSIX. acos(-1) is pi.
void to_cartesian(double r, double degrees, double *x, double *y) {
const double pi = acos(-1.0);
double t = degrees * pi / 180.0;
*x = r * cos(t);
*y = r * sin(t);
}
cartesian.h 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
#ifndef TO_CARTESIAN_H
#define TO_CARTESIAN_H
// Sets *x and *y to the point at the distance r and the angle in degrees.
void to_cartesian(double r, double degrees, double *x, double *y);
#endif
test_cartesian.c 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
#include "cartesian.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
double r, degrees, x, y;
};
static const struct test_case cases[] = {
{"east", 1.0, 0.0, 1.0, 0.0},
{"north", 2.0, 90.0, 0.0, 2.0},
{"west", 2.0, 180.0, -2.0, 0.0},
{"diagonal", 1.0, 45.0, 0.7071067811865476, 0.7071067811865476},
{"thirty-degrees", 2.0, 30.0, 1.7320508075688772, 1.0},
{"zero-radius", 0.0, 123.0, 0.0, 0.0},
{"south", 1.0, 270.0, 0.0, -1.0},
{"negative-angle", 1.0, -90.0, 0.0, -1.0},
{"full-turn", 1.0, 360.0, 1.0, 0.0},
{"two-turns", 3.0, 720.0, 3.0, 0.0},
{"negative-radius", -1.0, 0.0, -1.0, 0.0},
{"large-radius", 1000000.0, 60.0, 500000.0, 866025.4037844386},
};
static int close_to(double got, double want) {
return fabs(got - want) <= fmax(1e-9, 1e-12 * fabs(want));
}
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
double x, y;
to_cartesian(c->r, c->degrees, &x, &y);
if (!close_to(x, c->x) || !close_to(y, c->y)) {
printf("FAIL %s: (%.17g, %.17g)\n", c->name, x, y);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
using System;
/// <summary>Turns a distance and an angle in degrees into the coordinates x and y.</summary>
public static class Cartesian
{
/// <summary>Returns the point at the distance r and the angle in degrees.</summary>
public static (double X, double Y) ToCartesian(double r, double degrees)
{
double t = degrees * Math.PI / 180;
return (r * Math.Cos(t), r * Math.Sin(t));
}
}
CartesianTests.cs 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
using System;
using Xunit;
public sealed class CartesianTests
{
public static TheoryData<string, double, double, double, double> Cases => new()
{
{ "east", 1.0, 0.0, 1.0, 0.0 },
{ "north", 2.0, 90.0, 0.0, 2.0 },
{ "west", 2.0, 180.0, -2.0, 0.0 },
{ "diagonal", 1.0, 45.0, 0.7071067811865476, 0.7071067811865476 },
{ "thirty-degrees", 2.0, 30.0, 1.7320508075688772, 1.0 },
{ "zero-radius", 0.0, 123.0, 0.0, 0.0 },
{ "south", 1.0, 270.0, 0.0, -1.0 },
{ "negative-angle", 1.0, -90.0, 0.0, -1.0 },
{ "full-turn", 1.0, 360.0, 1.0, 0.0 },
{ "two-turns", 3.0, 720.0, 3.0, 0.0 },
{ "negative-radius", -1.0, 0.0, -1.0, 0.0 },
{ "large-radius", 1000000.0, 60.0, 500000.0, 866025.4037844386 },
};
private static bool Close(double got, double want) =>
Math.Abs(got - want) <= Math.Max(1e-9, 1e-12 * Math.Abs(want));
[Theory]
[MemberData(nameof(Cases))]
public void ToCartesian(string name, double r, double degrees, double wantX, double wantY)
{
Assert.NotNull(name);
var (x, y) = Cartesian.ToCartesian(r, degrees);
Assert.True(Close(x, wantX), $"x = {x}");
Assert.True(Close(y, wantY), $"y = {y}");
}
[Fact]
public void Constants()
{
Assert.True(Close(Math.Atan2(0, -1), Math.PI));
Assert.Equal(4.0, Math.Sqrt(16));
Assert.Equal(1024.0, Math.Pow(2, 10));
Assert.True(Close(Math.Log(Math.E), 1));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
/** Returns the point [x, y] at the distance r and the angle in degrees. */
export function toCartesian(r, degrees) {
const t = (degrees * Math.PI) / 180;
return [r * Math.cos(t), r * Math.sin(t)];
}
cartesian.test.js 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toCartesian } from "./cartesian.js";
const cases = [
["east", 1, 0, [1, 0]],
["north", 2, 90, [0, 2]],
["west", 2, 180, [-2, 0]],
["diagonal", 1, 45, [0.7071067811865476, 0.7071067811865476]],
["thirty-degrees", 2, 30, [1.7320508075688772, 1]],
["zero-radius", 0, 123, [0, 0]],
["south", 1, 270, [0, -1]],
["negative-angle", 1, -90, [0, -1]],
["full-turn", 1, 360, [1, 0]],
["two-turns", 3, 720, [3, 0]],
["negative-radius", -1, 0, [-1, 0]],
["large-radius", 1000000, 60, [500000, 866025.4037844386]],
];
const close = (got, want) => Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));
for (const [name, r, degrees, want] of cases) {
test(name, () => {
const [x, y] = toCartesian(r, degrees);
assert.ok(close(x, want[0]), `x = ${x}`);
assert.ok(close(y, want[1]), `y = ${y}`);
});
}
test("constants", () => {
assert.ok(close(Math.atan2(0, -1), Math.PI));
assert.equal(Math.sqrt(16), 4);
assert.equal(2 ** 10, 1024);
assert.equal(2 ^ 10, 8);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
/** Returns the point [x, y] at the distance r and the angle in degrees. */
export function toCartesian(r: number, degrees: number): [number, number] {
const t = (degrees * Math.PI) / 180;
return [r * Math.cos(t), r * Math.sin(t)];
}
cartesian.test.ts 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toCartesian } from "./cartesian.ts";
const cases: [string, number, number, [number, number]][] = [
["east", 1, 0, [1, 0]],
["north", 2, 90, [0, 2]],
["west", 2, 180, [-2, 0]],
["diagonal", 1, 45, [0.7071067811865476, 0.7071067811865476]],
["thirty-degrees", 2, 30, [1.7320508075688772, 1]],
["zero-radius", 0, 123, [0, 0]],
["south", 1, 270, [0, -1]],
["negative-angle", 1, -90, [0, -1]],
["full-turn", 1, 360, [1, 0]],
["two-turns", 3, 720, [3, 0]],
["negative-radius", -1, 0, [-1, 0]],
["large-radius", 1000000, 60, [500000, 866025.4037844386]],
];
const close = (got: number, want: number): boolean =>
Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));
for (const [name, r, degrees, want] of cases) {
test(name, () => {
const [x, y] = toCartesian(r, degrees);
assert.ok(close(x, want[0]), `x = ${x}`);
assert.ok(close(y, want[1]), `y = ${y}`);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
// Package cartesian turns a distance and an angle in degrees into the
// coordinates x and y.
package cartesian
import "math"
// ToCartesian returns the point x, y at the distance r and the angle in
// degrees.
func ToCartesian(r, degrees float64) (x, y float64) {
t := degrees * math.Pi / 180
return r * math.Cos(t), r * math.Sin(t)
}
cartesian_test.go 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
package cartesian
import (
"math"
"testing"
)
var cases = []struct {
name string
r, degrees float64
x, y float64
}{
{"east", 1.0, 0.0, 1.0, 0.0},
{"north", 2.0, 90.0, 0.0, 2.0},
{"west", 2.0, 180.0, -2.0, 0.0},
{"diagonal", 1.0, 45.0, 0.7071067811865476, 0.7071067811865476},
{"thirty-degrees", 2.0, 30.0, 1.7320508075688772, 1.0},
{"zero-radius", 0.0, 123.0, 0.0, 0.0},
{"south", 1.0, 270.0, 0.0, -1.0},
{"negative-angle", 1.0, -90.0, 0.0, -1.0},
{"full-turn", 1.0, 360.0, 1.0, 0.0},
{"two-turns", 3.0, 720.0, 3.0, 0.0},
{"negative-radius", -1.0, 0.0, -1.0, 0.0},
{"large-radius", 1000000.0, 60.0, 500000.0, 866025.4037844386},
}
func near(got, want float64) bool {
return math.Abs(got-want) <= math.Max(1e-9, 1e-12*math.Abs(want))
}
func TestToCartesian(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
x, y := ToCartesian(c.r, c.degrees)
if !near(x, c.x) || !near(y, c.y) {
t.Fatalf("got (%v, %v), want (%v, %v)", x, y, c.x, c.y)
}
})
}
}
func TestConstants(t *testing.T) {
if !near(math.Atan2(0, -1), math.Pi) || math.Sqrt(16) != 4 || math.Pow(2, 10) != 1024 {
t.Fatal("a constant or a function is wrong")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
/// Returns the point (x, y) at the distance r and the angle in degrees.
pub fn to_cartesian(r: f64, degrees: f64) -> (f64, f64) {
let t = degrees.to_radians();
(r * t.cos(), r * t.sin())
}
tests/cartesian_test.rs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
use algo_use_mathematical_constants_and_functions::to_cartesian;
use std::f64::consts::PI;
const CASES: &[(&str, f64, f64, (f64, f64))] = &[
("east", 1.0, 0.0, (1.0, 0.0)),
("north", 2.0, 90.0, (0.0, 2.0)),
("west", 2.0, 180.0, (-2.0, 0.0)),
("diagonal", 1.0, 45.0, (0.7071067811865476, 0.7071067811865476)),
("thirty-degrees", 2.0, 30.0, (1.7320508075688772, 1.0)),
("zero-radius", 0.0, 123.0, (0.0, 0.0)),
("south", 1.0, 270.0, (0.0, -1.0)),
("negative-angle", 1.0, -90.0, (0.0, -1.0)),
("full-turn", 1.0, 360.0, (1.0, 0.0)),
("two-turns", 3.0, 720.0, (3.0, 0.0)),
("negative-radius", -1.0, 0.0, (-1.0, 0.0)),
("large-radius", 1000000.0, 60.0, (500000.0, 866025.4037844386)),
];
fn close(got: f64, want: f64) -> bool {
(got - want).abs() <= f64::max(1e-9, 1e-12 * want.abs())
}
#[test]
fn cases() {
for &(name, r, degrees, (x, y)) in CASES {
let (gx, gy) = to_cartesian(r, degrees);
assert!(close(gx, x) && close(gy, y), "{name}: got ({gx}, {gy})");
}
}
#[test]
fn constants() {
assert!(close(0f64.atan2(-1.0), PI));
assert_eq!(16f64.sqrt(), 4.0);
assert_eq!(2f64.powi(10), 1024.0);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
# to_cartesian R DEGREES
# Prints "x y" with 6 decimals. Bash arithmetic has only integers, so awk
# does the floating-point work. A value that rounds to zero prints as 0.
to_cartesian() {
awk -v r="$1" -v d="$2" 'BEGIN {
pi = atan2(0, -1)
t = d * pi / 180
x = r * cos(t); y = r * sin(t)
if (x > -5e-7 && x < 5e-7) x = 0
if (y > -5e-7 && y < 5e-7) y = 0
printf "%.6f %.6f\n", x, y
}'
}
test_cartesian.bats 31 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-mathematical-constants-and-functions/.
setup() {
source "$BATS_TEST_DIRNAME/cartesian.sh"
}
# close GOT_X GOT_Y WANT_X WANT_Y: the output has 6 decimals.
close() {
awk -v a="$1" -v b="$2" -v c="$3" -v d="$4" 'BEGIN {
e = a - c; if (e < 0) e = -e
f = b - d; if (f < 0) f = -f
exit !(e < 1e-6 && f < 1e-6)
}'
}
@test "east" { run to_cartesian 1 0; [ "$status" -eq 0 ]; close $output 1 0; }
@test "north" { run to_cartesian 2 90; [ "$status" -eq 0 ]; close $output 0 2; }
@test "west" { run to_cartesian 2 180; [ "$status" -eq 0 ]; close $output -2 0; }
@test "diagonal" { run to_cartesian 1 45; [ "$status" -eq 0 ]; close $output 0.7071067811865476 0.7071067811865476; }
@test "thirty-degrees" { run to_cartesian 2 30; [ "$status" -eq 0 ]; close $output 1.7320508075688772 1; }
@test "zero-radius" { run to_cartesian 0 123; [ "$status" -eq 0 ]; close $output 0 0; }
@test "south" { run to_cartesian 1 270; [ "$status" -eq 0 ]; close $output 0 -1; }
@test "negative-angle" { run to_cartesian 1 -90; [ "$status" -eq 0 ]; close $output 0 -1; }
@test "full-turn" { run to_cartesian 1 360; [ "$status" -eq 0 ]; close $output 1 0; }
@test "two-turns" { run to_cartesian 3 720; [ "$status" -eq 0 ]; close $output 3 0; }
@test "negative-radius" { run to_cartesian -1 0; [ "$status" -eq 0 ]; close $output -1 0; }
@test "large-radius" { run to_cartesian 1000000 60; [ "$status" -eq 0 ]; close $output 500000 866025.4037844386; }
@test "zero-prints-as-zero" { run to_cartesian 1 90; [ "$output" = "0.000000 1.000000" ]; }
References
- Rosetta Code, Real constants and functions (task text, from acmeism/RosettaCodeData), task text
- The Python Standard Library, math, Constants; Angular conversion; Trigonometric functions; math.isclose; math.pow
- MDN Web Docs, Math, Description; Static properties
- Java SE 25 API, Class Math, toRadians(double)
- .NET API reference, Math class, Fields; Methods
- Go standard library, math, Constants; func Log; func Sqrt
- Rust standard library, module std::f64::consts, Constants
- Rust standard library, primitive type f64, to_radians
- The Open Group Base Specifications Issue 8, math.h, the table of symbolic constants
- cppreference.com, Mathematical constants, Constants
- Bash Reference Manual, 6.5 Shell Arithmetic
- The Open Group Base Specifications Issue 8, awk, Arithmetic Functions
- MDN Web Docs, Bitwise XOR (^), the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag CNJ3Z0 Edit this page History Report an error Markdown