Home > OS >  How do create a python function that can take the cube root of fractions that can return the answer
How do create a python function that can take the cube root of fractions that can return the answer

Time:06-20

How do I write a python def function that can take the cube roots of fractions and returning the answer as a fraction with a rationalized denominator? For example, ³⎷10 / ³⎷56 = ³⎷490/14 or ³⎷1 / ³⎷27 = 1/3?

CodePudding user response:

You really need to be more clear about what you want to achieve but here is an answer based on what I could understand from your question:

You need to look into the Fractions module. Here is script that does what you explained in your second example.

from fractions import Fraction

def cuberoot(number: float) -> float:
    if number < 0:
        number = abs(number)
        cube_root = number**(1/3)*(-1)
    else:
        cube_root = number**(1/3)
    return cube_root

def cube_root_fraction(initial_fraction: Fraction) -> Fraction:
    numerator = int(cuberoot(initial_fraction.numerator))
    denominator =  int(cuberoot(initial_fraction.denominator))
    return Fraction(numerator, denominator)
 
initial_fraction = Fraction(1, 27)
result = cube_root_fraction(initial_fraction)
print(result)

Input:

Fraction(1, 27)

Output:

1/3

CodePudding user response:

To get rid of the cube root in the denominator, we can multiply both numerator and denominator with the square of that cube root. For example:

      ³⎷10 / ³⎷56 = ³⎷10(³⎷56)² / ³⎷56(³⎷56)² = ³⎷(10⋅56²) / 56

Then factors should be found in the number whose cube root is taken in the numerator. We can use a prime factorisation function for that purpose. If there are factors that are cubes, they can be extracted out of the cube root. In the example, we can write the fraction as:

      ³⎷(10⋅56²) / 56 = ³⎷(4³490) / 56 = 4(³⎷490) / 56

And then finally we can divide both the coefficient part of the numerator and the denominator by their greatest common divisor, and so we get:

      4(³⎷490) / 56 = ³⎷490 / 14

In case there is a coefficient in the numerator that remains, we can bring it back inside the cube root. This is not applicable in this example.

from math import gcd, prod

def prime_factors(n):
    i = 2
    while i * i <= n:
        freq = 0
        while n % i == 0:
            n //= i
            freq  = 1
        if freq:
            yield i, freq
        i  = 1
    if n > 1:
        yield n, 1

def rationalize(root3nominator, root3denominator):
    root3nominator *= root3denominator * root3denominator
    product = gcd(root3denominator, prod(factor ** (freq // 3)
        for factor, freq in prime_factors(root3nominator)
        if freq >= 3))
    return (root3nominator // (product*product*product),
            root3denominator // product)

# Example runs   
print(rationalize(10, 56))  # (490, 14)
print(rationalize(1, 27))   # (1, 3)
  • Related