0

I am currently having some problems involving trigonometric functions with Python's Math library. What I am trying to do is to get the tangent of 45°, which is equal to 1. Since math.tan only accepts values in radians, I convert 45 to radians, as shown below:

math.tan(math.radians(45))

The value returned, however, is not equal to 1, but almost: 0.9999999999999999. This can be proofed comparing:

math.tan(math.radians(45)) == 1
# >>> False

I am aware that this concerns float imprecision and its tricky nature (plus function concatenation, which increases imprecision), but I would like to know how to mitigate it, and, if it is possible, to get 1 as the result.

Pedro
  • 194
  • 5
  • This is problematic in raw python because of how it treats floats, but can be solved easily with a [3rd-party symbolic solver](https://docs.sympy.org/latest/tutorial/simplification.html#trigonometric-simplification) `from sympy import *; deg_to_rad = lambda d: d * pi / 180 ; print(tan(deg_to_rad(45)))` : 1 ... `tan(deg_to_rad(60))`: sqrt(3) .. use `.evalf()` for decimal output – ti7 Feb 25 '21 at 17:49
  • Some further examples: `tan(deg_to_rad(45)).evalf() == 1`: True .. `tan(deg_to_rad(61)).evalf()`: 1.80404775527142 – ti7 Feb 25 '21 at 17:55
  • 1
    It is possible to mitigate this specific case, but what good does that do you? Only a few special cases of trigonometric functions have rational values for rational operands (whether in degrees or radians). Irrational numbers **cannot** be exactly represented in any numerical format (they can in symbolic or specialized formats). So you must have approximate results in almost all cases, either because the irrational operand is approximated or because the irrational result is approximated. So what is the overall goal? Generally, the correct way to use floating-point is to accept approximations. – Eric Postpischil Feb 25 '21 at 20:53
  • " how to mitigate it," --> Convert the degrees to a sub-range [-22.5...22.5], convert to radians, call trig function, use trig properties to re-build answer. [Sample](https://stackoverflow.com/a/31525208/2410359) reduces by to [-45...45] , but the principle is the same. – chux - Reinstate Monica Feb 25 '21 at 21:30

0 Answers0