division gives 0 in loop, why? - python-2.7

the code below gives me 0% for each 20th iteration, instead of the actual percentage I would like it to show.
n=100
for i in range(n):
if i% 20 ==0:
print str(i/n*100) + '%, Progress'
Results:
0%, Progress
0%, Progress
etc.....
I must be missing something really simple. Thank you.

change the division to i/(float)n*100 so that the resulting output will be formatted to decimal points by the python interpreter.

Division automatically rounds down to the nearest integer.
What happens in your code is:
i = 20
n = 100
i/n = 20/100, which becomes 0.
Then (i/n)*100 = 0*100 = 0.
You could solve this by first multiplying i by 100 and then dividing by n:
i*100/n

n=100
for i in range(n):
print(i);
if i% 20 ==0:
print str((float(i)/float(n))*100) + '%, Progress'
for python i/n is an (int)/(int) according to your variable declaration. so ti tries to give an int answer for i/n which is always 0.

In each iteration i/n*100 gets rounded down to the nearest integer (this is how the division operator works on integers in python2).
You could either use explicit casting to float() or execute from __future__ import division beforehand. This would prevent the division operator from rounding down automatically.
Here you can find a detailed description of a similar problem.

Related

Primes in arithmetic progressions in Sagemath

I am in need of finding prime numbers in arithmetic progression
80218110*n+8021749, n=1 to 100,000
I was told that using Sage would be a good option, since my computer is old. I happen to be new to Sage and I haven't found it to solve my problem, I guess it shouldn't be difficult, does anyone have a good reference for printing primes in arithmetic progressions?
SageMath is based on Python, and Python provides a syntax which should be comfortable for mathematicians:
[80218110*n + 8021749 for n in range(100)]
range(100) is the ordered set 0, 1, 2, ..., 99, and so the previous line evaluates 80218110*n + 8021749 for these values of n. We can also test whether the entries are prime:
INPUT: [80218110*n+8021749 for n in range(100) if (80218110*n+8021749).is_prime()]
OUTPUT:
[8021749,
489330409,
569548519,
970639069,
1050857179,
1131075289,
1772820169,
2093692609,
2173910719,
3136528039,
3617836699,
4660672129,
4740890239,
5382635119,
6425470549,
7067215429,
7227651649,
7548524089]
You can of course make the argument to range larger, but maybe it's not a good idea to print the whole list.
INPUT: len([80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()])
OUTPUT: 15273
(len returns the length of the list.) Producing this list is pretty quick, at least on my computer:
INPUT: %time L = [80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()]
OUTPUT CPU times: user 94.6 ms, sys: 1.13 ms, total: 95.8 ms
Wall time: 95.5 ms
(ms is milliseconds.)

How do I eliminate even numbers from this python code without an infinite loop occurring?

I have tried different ways to try print odd numbers only but its only causing an infinite loop to occur. Could you please assist me?
import sys
i = 1
while i < len(sys.argv):
print sys.argv[i]
i = i + 1
Your question is little bit confusing.
You should be processing all arguments and then decide which one you should print.
import sys
i = 1
while i < len(sys.argv):
number = int(sys.argv[i])
if number % 2 == 1:
print number
i = i + 1
In python, sys.argv contains only one item 'main.py' in index number 0.
So, if you run the program from index 1, you will get nothing as output. If you set it from index 0, you will get 'main.py' printed as output.
If this answer is not satisfactory, please clarify your issue with this code.

"ROUND" calculation can't be lower than 1.0

I need a ROUND calculation to always round up when it lands between 0 and 1 (but not when it's a value above these numbers), but can't seem to figure out how to make it work.
This is what I have currently:
=ROUND(100/DATA!H6)
try:
=IF((100/DATA!H6>0)*(100/DATA!H6<1), ROUNDUP(100/DATA!H6, ), 100/DATA!H6)

Python counter percentages returning 0 [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 4 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

c++ random numbers -100 to 100

I want to generate a list that contains random numbers from -100 to 100. The code I have so far just goes from -50 to 50.
for(int line=0;line<100;line++) //reads individual lines and compares them
{
ofs<<rand()%101 + (-50)<<endl;
}
I would really appreciate it if someone could point me in the right direction!
Change to %201 and +(-100). A little experimentation would have figured this out.
Note that you want values from -100 to +100, which is a range of 200 values, so you'd really want:
rand() % 200 // possible off-by-one error
This will give you 0..199. To get closer to the range you want, subtract 99:
(rand() % 200) - 99
This will give you the range -99..+100. This is closer to what you want.
You should be able to go back now and tweak to get the range you really want.
rand() %201 - 100 works just right