How can I make an output in radians with pi in it?

966 views Asked by At

I want to give out an angle in radians in python. I also know how to do that but is it posible to make the output like that 1 * pi instead of 3.14159 without programming it myself?

Thx for help.

2

There are 2 answers

0
Phoenixo On BEST ANSWER

Just like this (cf furas's comment) :

from math import pi

angle = 2*pi
angle_new_format = angle/pi
print("angle =", angle)
print("angle_new_format = {} * pi".format(angle_new_format))

Output :

angle = 6.283185307179586
angle_new_format = 2.0 * pi
0
Stef On

I wrote this function, which will find a nice fraction of pi using Fraction.limit_denominator, and then cleans up the output to write "pi" instead of "pi/1" and "0" instead of "0.0 pi", etc.

from math import pi
from fractions import Fraction

def rad_to_pifrac(rad, max_denominator=8000):
    pifrac = Fraction(rad / pi).limit_denominator(max_denominator)
    if pifrac == 0:
        return '0'
    num = {1: '', -1: '-'}.get(pifrac.numerator, str(pifrac.numerator))
    denom = '/{}'.format(pifrac.denominator) if pifrac.denominator != 1 else ''
    return 'pi'.join((num, denom))

By toying with the optional parameter max_denominator you can adjust between rounder fractions or more accurate fractions; for instance, rad_to_pifrac(22/7, max_denominator=1000) is 'pi' but rad_to_pifrac(22/7, max_denominator=2000) is '2001pi/2000'.

Some tests:

import sympy

def test_pi(max_denominator=100):
    testcases = ['0', '1', '22/7', '0.39', '0.393', '3', '3.14', 'pi/8', 'pi/4', '-pi/4', '3*pi/4', '-3*pi/4', '-pi', 'pi', '2*pi', '6.28']
    print('max_denominator={}'.format(max_denominator))
    for s in testcases:
        value = float(sympy.parse_expr(s).evalf())
        pifrac = rad_to_pifrac(value, max_denominator=max_denominator)
        print('{:10s} ----> {}'.format(s, pifrac))

>>> test_pi()
max_denominator=100
0          ----> 0
1          ----> 7pi/22
22/7       ----> pi
0.39       ----> 12pi/97
0.393      ----> pi/8
3          ----> 85pi/89
3.14       ----> pi
pi/8       ----> pi/8
pi/4       ----> pi/4
-pi/4      ----> -pi/4
3*pi/4     ----> 3pi/4
-3*pi/4    ----> -3pi/4
-pi        ----> -pi
pi         ----> pi
2*pi       ----> 2pi
6.28       ----> 2pi