Create a Python function that calculates the average of 3 numbers - python

I am trying to create a Python function that calculates the average of 3 temperatures. I am a beginner at Python so I wanted to make sure I am on the right track.
This is what I have so far:
def average(temp_one, temp_two, temp_three):
avg = (int(temp_one) + int(temp_two) + int(temp_three))/3
return avg
Then I have to use the function created that prompts for 3 temperatures and calculates the average. The average output must include one decimal place.
def average(temp_one, temp_two, temp_three):
avg = (int(temp_one) + int(temp_two) + int(temp_three))/3
return (avg)
temp_one = float(input(“Enter temperature one:”))
temp_two = float(input(“Enter temperature two:”))
temp_three = float(input(“Enter temperature three:”))
average = ( temp_one+ temp_two + temp_three ) // 3
print (average(temp_one, temp_two, temp_three))
For this part I am not very sure of.. Any help is appreciated, thank you!

1. Your calculation is doing unnecessary casts to int which loses some precision. In fact, it truncates decimal places, thus lowers your average artificially.
2. You are not using the function you have written. Instead you repeat your calculation code with integer division //. Note that:
5 / 2 == 2.5 # floating point division
5 // 2 == 2 # integer division
so here, you are losing information as well.
3. You should format your output to one decimal place. This is best done using string formatting
Thus:
def average(temp_one, temp_two, temp_three):
return (temp_one + temp_two + temp_three) / 3
# why cast to int and lose precision
# read your 3 float inputs ...
avg = average(temp_one, temp_two, temp_three) # actually use your function
print('{:.1f}'.format(avg)) # format output

"%0.1f"%my_float
#or
"{0:0.1f}".format(my_float)
#or
"{my_float:0.1f}".format(my_float=my_float)
will print a float with 1 decimal place see also python format strings

Related

How to get float to two decimal places without rounding off

Like if I have a 8.225 I want 8.22 not 8.23. DO I have to use it as a string first then convert to float? Or is there a simpler way?
Could not print the decimal without rounding off.
yes . you can use a string for converting.
Like this : num = '8.225' num = float(num) print(type(num)) print('Float Value =', num)
I think this code can solve your problem.
You may take reference from below python function which shall convert a float to 2 decimal places without rounding off:
def round2(x):
return float(str(x)[:str(x).index('.')+3])
Alternatively, You can also convert to int after multiplying by 100 then divide again by 100 :
def round_to_2(x):
return int(x * 100) / 100
Usually there wouldn't be any performance difference b/w two unless same operations is repeated millions of times in a loop.

Python Single Decimal

When I enter this code the answer ends with 2 characters behind the decimal. How do I make this only have 1 number behind it?
tempature=float(input("Enter the temp(F):"))
formant_tempature = f"{tempature:2f}"
print(round(((int(tempature)-32)*5/9)+273.15,2))
When you used round function you have specified that you want two decimal places. Just replace 2 with a number 1.
print(round(((int(tempature)-32)*5/9)+273.15,1))
You are using the string formatting operator for that ( formant_tempature = f"{tempature:2f}" )
What about formant_tempature = f"{tempature:1f}"
Like if you want it to display 5 decimals, just change it to f"{tempature:5f}"
And so on.
And for the round method, change 2 to 1.
I'm not sure why you'd do any math just to present this rounded, when you can simply use an f-string to specify outputting the temperature with a single decimal place precision.
>>> temperature = 43.8934
>>> print(f"Temperature is {temperature:.1f} degrees")
Temperature is 43.9 degrees
>>> print(f"Temperature is {temperature * 1.8 + 32:.1f} degrees farenheit")
Temperature is 111.0 degrees farenheit

How to convert a floating-point number to a fixed-width string?

I tried to find this question answered, but I haven't found anything related.
I have a variable that can be in a format like 50000.45 or in a format like 0.01.
I need to write this variable in a label that is 4 digits wide.
What is the best way to fit the label showing only the most significant digits?
To better explain, I would like to have for example:
for 50000.45: 50000
for 4786.847: 4786
for 354.5342: 354.5
for 11.43566: 11.43
and for 0.014556: 0.0145
Possibly without having to do:
if ... < variable < ...:
round(variable,xx)
for all cases.
In order to convert a number into a set number of digits, you can convert the number into only decimals (aka 0 <= n <= 1), then remove the last characters. You can do it like that:
from math import log10
number = 123.456789
n_digits = 4
log = int(log10(number) + 1)
number /= 10**log # convert the number into only decimals
number = int(number*10**n_digits)/10**n_digits # keep the n first digits
number *= 10**log # multiply the number back
Or a more compact form:
from math import log10
number = 123.456789
n_digits= 4
log = int(log10(number) + 1) - n_digits
number = int(number/10**log)*10**log
[Edit] You should use Python round() function in a simpler way:
number = round(number, n_digits-int(log10(number))-1)

How do I make a float only show a certain amount of decimals

I have a float that has 16 decimal places, but I want it to be capped at 6, and if I ever get a float that has less than 6 decimals, I want it to add 0s until it has 6.
i.e.:
1.95384240549 = 1.953842
3.12 = 3.120000
I'm trying to generate a value based on a certain amount of demand an object has. Thanks!
To round to a certain amount of decimals you can use round()
Example:
round(1.95384240549,6) > 1.953842
And for more 0's after the decimal place you can use format():
format(3.12, '.6f') > '3.120000'
Note this is of type string
Read more here:
Rounding syntax
Format syntax
A bit more complex than the previous answer, but more consistent.
import math
def truncate(number, digits) -> float:
places = len(str(number)[str(number).find("."):])
if places > 6:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
else:
return str(number) + "0"*(6 - places)
Examples: truncate(3.12 , 6) returns 3.120000 and truncate(1.95384240549, 6) returns 1.953842

Prevent Rounding to Zero in Python

I have a program meant to approximate pi using the Chudnovsky Algorithm, but a term in my equation that is very small keeps being rounded to zero.
Here is the algorithm:
import math
from decimal import *
getcontext().prec = 100
pi = Decimal(0.0)
C = Decimal(12/(math.sqrt(640320**3)))
k = 0
x = Decimal(0.0)
result = Decimal(0.0)
sign = 1
while k<10:
r = Decimal(math.factorial(6*k)/((math.factorial(k)**3)*math.factorial(3*k)))
s = Decimal((13591409+545140134*k)/((640320**3)**k))
x += Decimal(sign*r*s)
sign = sign*(-1)
k += 1
result = Decimal(C*x)
pi = Decimal(1/result)
print Decimal(pi)
The equations may be clearer without the "decimal" terms.
import math
pi = 0.0
C = 12/(math.sqrt(640320**3))
k = 0
x = 0.0
result = 0.0
sign = 1
while k<10:
r = math.factorial(6*k)/((math.factorial(k)**3)*math.factorial(3*k))
s = (13591409+545140134*k)/((640320**3)**k)
x += sign*r*s
sign = sign*(-1)
k += 1
result = C*x
pi = 1/result
print pi
The issue is with the "s" variable. For k>0, it always comes to zero. e.g. at k=1, s should equal about 2.1e-9, but instead it is just zero. Because of this all of my terms after the first =0. How do I get python to calculate the exact value of s instead of rounding it down to 0?
Try:
s = Decimal((13591409+545140134*k)) / Decimal(((640320**3)**k))
The arithmetic you're doing is native python - by allowing the Decimal object to perform your division, you should eliminate your error.
You can do the same, then, when computing r.
A couple of comments.
If you are using Python 2.x, the / returns an integer result. If you want a Decimal result, you convert at least one side to Decimal first.
math.sqrt() only return ~16 digits of precision. Since your value for C will only be accurate to ~16 digits, your final result will only be accurate to 16 digits.
If you're doing maths in Python 2.x, you should probably be putting this line into every module:
from __future__ import division
This changes the meaning of the division operator so that it will return a floating point number if needed to give a (closer to) precise answer. The historical behaviour is for x / y to return an int if both x and y are ints, which usually forces the answer to be rounded down.
Returning a float if necessary is generally regarded as a better way to handle division in a language like Python where duck typing is encouraged, since you can just worry about the value of your numbers rather than getting different behaviour for different types.
In Python 3 this is in fact the default, but since old programs relied on the historical behaviour of the division operator it was felt the change was too backwards-incompatible to be made in Python 2. This is why you have to explicitly turn it on with the __future__ import. I would recommend always adding that import in any module that might be doing any mathematics (or just any module at all, if you can be bothered). You'll almost never be upset that it's there, but not having it there has been the cause of a number of obscure bugs I've had to chase.
I feel that the problem with 's' is that all terms are integers, thus you are doing integer maths. A very simple workaround, would be to use 3.0 in the denominator. It only takes one float in the calculation to get a float returned.

Categories