I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
def eq_of_form():
print "Eq of the form y = ax^m + bx^n + c " + ":"
def value_of_a():
return raw_input("Enter value for a \n")
def value_of_b():
return raw_input("Enter value for b \n")
def value_of_c():
return raw_input("Enter value for c \n")
def value_of_m():
return raw_input("Enter value for m \n")
def value_of_n():
return raw_input("Enter value for n \n")
def value_of_x():
return raw_input("Enter a value for x to find " +
"value of y and the gradient at that point \n " + "x = ")
def area_under_graph():
y = (int(value_of_a())*int(value_of_x())**(int(value_of_m())+1))/((int(value_of_m())+1))
// * 2nd part.This works for me(:
// + (int(value_of_b())) * (int(value_of_x())**
// (int(value_of_n())+1))/(int(value_of_n())+1) + ((int(value_of_c())*int(value_of_x())))
print y
main()
(* Note: the eq under the area_under_graph() function is only half of it because the other half kind of work so I did not post it:))
For the top code, I tried inputting the values here: (maybe you can try using the same(: )
a = 1
b = 2
c = 1
m = 2
n = 1
x = 1
I am supposed to get 7/3 which is 2.333, but I end up getting 2. The problem appears to lie in the first part of the eq.
Sorry for the newbie question.
Your code at the start is wrong. You need to assign your variables after you read the user input:
value_of_a()
should be:
a = value_of_a()
It is also unnecessary to write a separate function for inputting each variable. You could instead have a function that takes a parameter:
def get_user_value(name):
return raw_input("Enter value for %s\n" % name)
a = get_user_value("a")
b = get_user_value("b")
# etc..
But then you ignore all these values and read them again inside the area_under_curve() method. This is probably not what you intend to do. Furthermore inside this method you assume that all parameters are integers. If you are using Python 2.5 the division here is integer division:
m1/m2
This could return 0 when the result was actually supposed to be a non-integer like 0.125. You need to use floats instead of integers to do the calculation. You can do this in Python 2.5 using float(m). In Python 3.0 the division operator does what you want by default.
/ does Integer division in Python2, this means a/b is the biggest integer c with c*b <=a, so 7/3 is indeed 2. You want floats, so you need to use them .. replace all the int with float in your code.
You should probably take another look at functions too ... you code can be much much shorter :-)
In Python 2.x, dividing an integer by another integer results in an integer. Either use from __future__ import division, or turn one of the integers into a float by passing it to float().
The issue is that you're using integer arithmetic - see all those int calls you've got everywhere. Integer arithmetic (in Python 2.x) will only ever return integers, so you'll never get 2.33, only 2.
Use float() instead of int() and things should work.
Related
I want to take user input and add each number up to 0. For example user inputs 9 I want to add 9+8+7+6.... +1 and output the total. My code
def main(*args):
sum = 0
for i in args:
sum = i + (i - 1)
return sum
result = main(9)
print(result)
comes close, but I can't get it to iterate through until 0. I've tried adding ranges in a few ways but no luck there. I'm stuck.
Let's say the user input is assigned to x, then the most simplistic answer is:
sum(range(int(x)+1))
Note that range() will generate a list (actually, an immutable sequence type in Python 3) of numbers up to, but not including, x, hence the +1.
In terms of your original code, there are a few issues. First, you should avoid naming variables the same as Python built-ins, such as sum. Second, you are attempting to iterate through a tuple of input arguments (e.g. args = (9,) in your case), which will perform 9 + (9-1), or otherwise 17 and then return that sum as an output.
Instead, you could do something like:
def main(*args):
mysum = 0
for i in range(args[0]+1):
mysum = mysum + i
return mysum
result = main(9)
print(result)
Both solutions here will return 45.
Nth triangle number. No iteration needed.
def calculate_nth_triangle_number(value):
return value * (value + 1) / 2
Your code misuses a relatively advanced feature of Python, that is argument packing, where all the arguments supplied to a function are packed in a tuple.
What happens when you call main(9)? the loop is entered once (because calling the function with a single argument is equivalent to args = (9, ) in the body of the function) i takes only one value, i = 9 and you have sum = 9+8 = 17.
For your case I don't like a for loop, can you use a while loop? with a while your function follows exactly the definition of your task!
def my_sum(n):
result = 0
while n>0:
result = result + n
n = n - 1
return result
Note that the order of summation and decrease is paramount to a correct result... note also that sum is the name of a built-in function and it is considered bad taste to overload a built-in name with an expression of yours.
def do_timelapse(self, cmd):
self.final_fps = input("What will your final edit be at(FPS)?\n")
self.frame_interval = input("What is your Camera's Frame interval(Sec)")
self.original_frame_fps = 1/self.frame_interval
self.small_original = self.original_frame_fps/100
self.percentage = self.final_fps/self.small_original
print self.percentage
How do i resolve this error:
self.percentage = self.final_fps/self.small_original
ZeroDivisionError: integer division or modulo by zero ?
self.frame_interval = input("What is your Camera's Frame interval(Sec)")
it returns an integer, means that you're using python 2. So the next line
self.original_frame_fps = 1/self.frame_interval
probably issues 0 if self.frame_interval > 1
self.small_original = self.original_frame_fps/100
so self.small_original is zero
self.percentage = self.final_fps/self.small_original
so it crashes.
Fix: work with floats:
self.original_frame_fps = 1.0/self.frame_interval
and
self.small_original = self.original_frame_fps/100.0
(of course check that self.frame_interval isn't 0 either)
Alternatives:
use python 3, with just a small fix (and still the check for zero):
self.final_fps = int(input("What will your final edit be at(FPS)?\n"))
self.frame_interval = int(input("What is your Camera's Frame interval(Sec)"))
since input returns strings now (like raw_input does in python 3)
use python 3 division in python 2: add this at the start of your file:
from __future__ import division
My best guess is you are using Python 2.7 which returns an integer value on division of two int. For example:
>>> 5 / 100
0
That is the reason the value of self.small_original is getting set as 0. In order to fix it, you need to type-cast any of the numerator or denominator to float as:
>>> float(5) / 100
0.05 # returns float value
Hence, you need to update the line in your code with:
self.original_frame_fps = 1.0/self.frame_interval
# float here ^
and
self.small_original = self.original_frame_fps/100.0
# float value ^
I am writing a program that converts a decimal number into a binary. I made it that far and I stuck with a problem. In the code with print(aa).
I tried to get a binary form of given number but it prints 1. I think I have "return" function problem here how can I solve it. Also, when I print binaryform it prints like the way below. Shouldn't it print reversely I mean first 1 and then 11 and then 111 .......10111.
# Python program to convert decimal number into binary number using recursive function
def binary(n, binaryform,i):
if n >= 1:
digit= n % 2
binaryform += digit*i
#print(binaryform)
i*=10
binary(n/2, binaryform, i)
print("xxx", binaryform)
return binaryform
dec = int(input("Enter an integer: "))# Take decimal number from user
aa = binary(dec, 0, 1)
print(aa)
OUTPUT:
Enter an integer: 23
('xxx', 10111)
('xxx', 111)
('xxx', 111)
('xxx', 11)
('xxx', 1)
1
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. Python Documentation
You're writing a recursive function - that's fun and good.
Now consider what you do: you check the LOW part of the number. If the LOW part of the number is 1 or 0 you do something, but then you shrink the number and recurse, checking a new LOW part, but the new low part came from a HIGHER part originally.
So whatever you determine should actually be at the end of the string, not the beginning, when you come back from recursion.
That's your question about printing reversely, I think. And yes, except you should just assemble it reversely, and then print it normally.
Also, you're actually trying to construct a decimal integer that will print out as if it were a binary number. It would be a lot simpler if you just constructed a string: "10101".
If you just want to convert integer to binary, try this code here . It looks like this :
def binary(n):
b = ''
while n > 0:
b = str(n % 2) + b
n >>= 1
print(b)
binary(10)
I want to get the sum of all numbers within a list. My code is shown below; however, I am getting an error when I try to run it:
c = [795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x = x + c1
I am also trying to divide one number by another. However, the result is always zero:
y=(273591/21247633)*100
In the first case, you need to define x before you use it and use c1 instead of c:
x = 0
c=[795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x=x+c1
print x
You can try this code online here.
In the second case, you need to use floating point numbers instead of integers:
y=(273591/21247633.0)*100
print y
This is because the result of an integer-integer division in Python 2.x is also an integer. In this case, 273591 รท 21247633 = 0.0128763048571 so the result is rounded down to 0.
This has changed in Python 3.x, and you can enable the same behavior in Python 2.x as follows:
from __future__ import division
y=(273591/21247633)*100
print y
You forgot to initialize x to 0 and this statement should be x = x + c1 and not x = x + c
Probably those numbers are used as integers. Using their float value should help.
y = (float(273591)/21247633)*100
If you want to get a sum of numbers in a list, then use sum:
c = [795557,757894,711411,556286,477322,426243,361643,350722]
x = sum(c)
For the second one, int/int returns an int rounded down, so 273591/21247633 returns 0. Convert one (or all) of the numbers to float and it will work as awaited:
y = (273591. / 21247633.) * 100.
This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>