Home > Mobile >  How can I make a function that takes the log of a number and returns it with the answer rounded to 4
How can I make a function that takes the log of a number and returns it with the answer rounded to 4

Time:02-15

The prompt we were initially given says to create a function that receives a number as an argument and returns the log of that number rounded to 4 decimals places. I need the function to take the min_num and max_num as the arguments

This is my code:

def min_num():
    while True:
        i = int(input("What's your minimum value?"))
        if i > 0:
            return i
        print("ERROR. Minimum should be greater than 0")


def max_num(min_mum):
    while True:
        i = int(input("What's your maximum value?"))
        if i > min_num:
            return i 
        print(f"ERROR. Maximum value must be greater {min})")

 min_value = min_num()
 max_value = max_num(min_value)

CodePudding user response:

You could use the log function that comes with Python's math package.

The built-in round function takes the number of decimals to round to as the second argument. round could lead to problems with inaccuracies as opposed to using Decimal @alexpdev's answer, but I suppose that is not a problem for a homework exercise.

import math

def rounded_log(num: float, number_of_decimals: int, base: int) -> float:
    return round(
             math.log(num, base),
             number_of_decimals
           )


CodePudding user response:

Using the decimal module that comes with python you can specify the precision of floating point numbers.

import decimal
decimal.getcontext().prec=5

a = 1.65745678656
b = 2.4584583893

c = decimal.Decimal(a)   decimal.Decimal(b)

print(c)

the output would be 4.1159

For math functions you can try some of the Decimal object's methods. for example:

import math
import decimal
decimal.getcontext().prec = 4

num = 3999              # randomly chosen number
flt = math.log(num)     # uses math.log function

dec = decimal.Decimal(num)   # turns num into a Decimal instance
dec = dec.ln()               # uses the Decimal ln() method

# flt is 8.293799608846818
# dec is 8.294
# flt == dec (rounded to a precision of 4)

print(dec, flt)

the output would be 8.294 8.293799608846818

More info can be found in the python documentation for the module. https://docs.python.org/3/library/decimal.html

  • Related