Where can I convert x to float in this Python function? [duplicate] - python

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 8 years ago.
How can I make this function return and print a float:
x = input ("Enter 5 numbers:")
def average(x):
return sum(x) / len(x)
print average(x)

In python 2.x, int object divided by int yields int.
You should convert one (or both) of the operand to float to get float result:
>>> 10 / 2
5
>>> float(10) / 2
5.0
Or turn on true division using __future__ module:
>>> from __future__ import division
>>> 10 / 2
5.0

Related

Division in python2.7 does not produce decimal values [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
What is the difference between '/' and '//' when used for division?
(16 answers)
Closed 5 years ago.
Here is my project on a small scale. The purpose is to approximate pi. I know it isn't neat, but the algorithm is correct.
adds = 0
subtracts = 0
for x in range(0, 10):
adds += 1/(1 + 4*x)
subtracts += 1/(3 + 4*x)
print(adds) #DEBUGGING
print(subtracts) #DEBUGGING
pi = float(4*(adds + subtracts)
print(pi)
Seems like it should work, right? On python 3, the same exact code gives me an accurate answer. However, in 2.7.10, this happens in the shell:
===================== RESTART: C:/Python27/Scripts/pi.py
=====================
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
4.0
>>>
Can someone explain to me why this happens and how I can correct this? I have tried conventional methods like converting to strings, formatting, rounding, etc. but none of them work. It is like my variables are being saved as 1's and 0's despite their values constantly changing. Once again, the same code works fine on Python 3.
On python2, division between integers results in integer division with the final answer truncated to a whole number.
>>> 1 / 2
0
On python3, this is not the case, because division automatically results in a float result unless you use the // integer division operator explicitly.
You'll want to have at least one of the operands of float type:
>>> 1. / 2
0.5
for x in range(0, 10):
adds += 1. / (1 + 4 * x)
subtracts += 1. / (3 + 4 * x)
Note the 1. is 1.0.
On Python 2.7, x / y is integer division, but you can use Python 3's real division using __future__ division :
from __future__ import division
adds = 0
subtracts = 0
for x in range(0, 10):
adds += 1/(1 + 4*x)
subtracts += 1/(3 + 4*x)
print(adds) #DEBUGGING
print(subtracts) #DEBUGGING
pi = float(4*(adds + subtracts))
print(pi)
Out :
1.0
0.333333333333
1.2
0.47619047619
1.31111111111
0.5670995671
1.38803418803
0.633766233766
1.44685771745
0.686397812714
1.49447676507
0.729876073583
1.53447676507
0.76691311062
1.56895952369
0.799171175136
1.59926255399
0.827742603708
1.62628958102
0.853383629349
9.91869284146

math.cos function returning different value than calculator [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I have this function that takes in an x value and returns an output y value.
def function(x):
y = math.cos(x**2/2)/(math.log(x+2,2))
return y
When I call the function, I get:
print function(1)
>> 0.630929753571
But WolframAlpha has the value at x = 1 to be 0.553693
Which is the correct value?
This is because you are using Python 2, where the / operator does integer division. This would give you the correct answer in Python 3:
>>> def f(x):
... y = math.cos(x**2/2)/(math.log(x+2,2))
... return y
...
>>> f(1)
0.5536929495121011
In Python 3, using the // operator, does floor division:
>>> def f(x):
... y = math.cos(x**2//2)/(math.log(x+2,2))
... return y
...
>>> f(1)
0.6309297535714574
>>>
In Python 2, use y = math.cos(x**2/ 2.0) / (math.log(x+2,2))
you are dividing an int by another int which is greater: 1 / 2 and therefore getting the cosine of zero since python 2.7 does not evaluate integer divisions as floating point. Try:
def function(x):
y = math.cos(x ** 2 / 2.0) / (math.log(x + 2, 2))
return y
Python 2 division operator does integer division, unless you tell it it's a float.
If you change to x**2/2.0 you will get the correct answer, like wolfram alfa.
Python 2 rounds to integer when you divide integer by integer so use one float number (i.e 2.0) when you divide to get correct result
import math
def function(x):
y = math.cos(x**2/2.0)/(math.log(x+2,2))
return y
print function(1)

To find the lcm of two numbers [duplicate]

This question already has answers here:
Division in Python 3 gives different result than in Python 2
(3 answers)
Closed 6 years ago.
I was given the task to compute lcm of any two numbers.I have coded in python.The problem is when i compiled it under python2.7, i got a result which is different from , when i compiled under python3.
import sys
def gcd(a,b):
if b == 0:
return a
remainder = a % b
return gcd(b,remainder)
def lcm(a, b):
return int( (a*b) / gcd(a,b))
if __name__ == '__main__':
input = sys.stdin.read()
a, b = map(int, input.split())
print(int(lcm(a, b)))
Input
226553150 1023473145
Output
46374212988031352 (under python3.5)
46374212988031350 (under python2.7)
Can someone help me ?
In Python 2 the division operator / will perform integer division, and not float division, when dealing with two integers. You can force the Python 3 behavior in Python 2 by importing division from __future__
>>> from __future__ import division
>>> 2/3
1.5

How to perform ceiling-division in integer arithmetic? [duplicate]

This question already has answers here:
Is there a ceiling equivalent of // operator in Python?
(9 answers)
Closed 7 years ago.
It's basically returning the boxes_needed. 1 box can contain 10 items. So if the items typed by the user is 102 then the code should return 11 boxes.
Is there a way to divide that rounds upwards if there is a non-zero remainder?
For your use case, use integer arithmetic. There is a simple technique for converting integer floor division into ceiling division:
items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize
Alternatively, use negation to convert floor division to ceiling division:
num_boxes = -(items // -boxsize)
Negate before and after?
>>> -(-102 // 10)
11
from math import ceil
print(ceil(10.3))
11
You can try :
import math
math.ceil( x )

decimal values in a list after applying arithmetic operations on it [duplicate]

This question already has answers here:
float is OK, int gives wrong output python 2.7 [duplicate]
(2 answers)
Closed 7 years ago.
present_values = random.sample(xrange(1,1000),5)
print present_values
present_values1 = [(x / 9) * 5 for x in present_values]
print (present_values1)
present_values2 = [(x / 9) * 4 for x in present_values]
print present_values2
How to get the values of present_values1 and present_values2 variables as decimal numbers while i am getting integers right now?
In 2.7, dividing an integer by an integer will result in an integer. For example,
>>> 35 / 9
3
In order for arithmetic to not result in an integer, at least one of its operands must be a non-integer.
Convert present_values into a list of Decimals before doing arithmetic on it.
import random
from decimal import Decimal
present_values = random.sample(xrange(1,1000),5)
#choose one:
present_values = map(Decimal, present_values)
#or
present_values = [Decimal(x) for x in present_values]
print present_values
present_values1 = [(x / 9) * 5 for x in present_values]
print (present_values1)
present_values2 = [(x / 9) * 4 for x in present_values]
print present_values2
Now your results will be Decimals. Example output:
[Decimal('209'), Decimal('15'), Decimal('372'), Decimal('367'), Decimal('516')]
[Decimal('116.1111111111111111111111111'), Decimal('8.333333333333333333333333335'), Decimal('206.6666666666666666666666666'), Decimal('203.88888888888888888888
88889'), Decimal('286.6666666666666666666666666')]
[Decimal('92.88888888888888888888888888'), Decimal('6.666666666666666666666666668'), Decimal('165.3333333333333333333333333'), Decimal('163.11111111111111111111
11111'), Decimal('229.3333333333333333333333333')]
If you don't literally mean "the Decimal data type, found in the decimal module" and instead generally mean "any numerical data type that can represent numbers that have a decimal point", then you can do the same thing with floats.
present_values = [float(x) for x in present_values]
Alternative approach: in 3.X, dividing an integer by an integer may result in a non-integer. You can backport this behavior to 2.7 by doing:
from __future__ import division
Then the rest of your code should produce "decimal" output without any additional changes.

Categories

Resources