How to calculate pow() with modulo for real numbers? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to perform a power operation combined with a modulo. I have trouble performing this pow() function with real numbers.
This works fine for integers:
pow(2,6000,400) = 176
However, this returns an error with real numbers:
pow(1.4142, 6000, 400)
I have tried also the math.pow() function but it doesn't
work either... how can I get this to work with real numbers ?

The python function pow() accepts 2 or 3 arguments. In your case, pow(x,y,z) does x power y and applies a modulo z to the result. But the documentation is explicit:
If the second argument is negative, the third argument must be
omitted. If z is present, x and y must be of integer types, and y must
be non-negative.
So:
Your first call works fine, because the arguments comply with the requirements. Note that despite pow(2,6000) being a huge number, the result of the combined modulo operation can be calculated easily without overflow, by using properties on modular exponentiation of integers.
Your second call fails with an error, because the first argument is not an integer. The workaround would be to decompose your operation into pow(1.4142,6000) % 400, because modulo is defined for real numbers. Unfortunately, pow(1.4142,6000) is too big and causes an overflow error. This is because contrary to the python integers which are of unlimited range, real numbers are limited by the range of the C floating point encoding.
P.S.: I assumed that it's about python and not VB, because VB's pow() accepts only 2 arguments.
Edit: hint for a workaround
Here a little workaround that makes use of the fact that technically, a floating point number is not a mathematical real of unlimited precision, but a rational number. We can then make use of the numerator and denominator and use integer operations to master the huge numbers:
n=pow(14142,6000) # take the first argument multiplied by a 10 exponent to make it an integer
d=pow(10000,6000) # keep track of this 10 exponent
i=n//d # integer division to compute the integral value
r=n-d*i # remainder of the integer division
precision=6 # precision
f=r*pow(10,precision)//d # keep the 6 most significant digits
result=(i%400)+(f/pow(10,precision))
The result is 271.048181 to the 6th digit. I let you as an exercise the writing of a function that performs this in a less artisanal way.

Related

When does python's % (modulo) operator work faster? Are there any special numbers, cases? Prime numbers? [duplicate]

This question already has answers here:
How does Python implement the modulo operation?
(2 answers)
Modulo operator in Python [duplicate]
(5 answers)
Closed 3 years ago.
So I am implementing a custom hash function and I am not sure what kind of number and how big a number to choose. I have tried various prime numbers but I am not sure if % operator works faster for prime numbers. Actually, I am not sure if there are cases when modulo operator works faster or if there are any cases.
Maybe the answer lies within cython or some other low level implementation details?
From the Python online documentation:
The % (modulo) operator yields the remainder from the division of the
first argument by the second. The numeric arguments are first
converted to a common type. A zero right argument raises the
ZeroDivisionError exception. The arguments may be floating point
numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.)
The modulo operator always yields a result with the same sign as its
second operand (or zero); the absolute value of the result is strictly
smaller than the absolute value of the second operand 1.
6. Expressions - Binary arithmetic operations - Modulo operator
A prime number ads no necessary improvement of degradation, the operator behaviour prevails.
If your looking to get the division and remainder in one go, you're looking for the divmod() function.

how to convert binary to int using own algorithm python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to convert birnary to in using own algorithm.
Here is the code:
binary=""
decimal=""
while binary!="exit":
decimal= input(">>")
decimal = decimal
if decimal!="0":
n = len(decimal) -1
n = pow(n, 2)
print(n)
Input:
1010
Bad Output:
9
When I enter binary and check them with calculator they arent true.
I dont have big clue how to make it so sorry for mistakes in code.
Thanks for reply
You need to move the input (where the user enters a binary number) outside the loop that's processing it. Then you have string containing ones (1) and zeros (0) which you can loop through.
Starting at the right-hand end of the string, multiply that number (1 or 0) by 1 (let's call this multiplier the ordinal) and save the result as total.
Multiply the ordinal by 2.
Grab the next number (from the right) from the input string and multiply it by the ordinal, add the result to total.
Keep going, multiplying the ordinal and using that to multiply the next number from the input string, until you run out of "numbers" in the input string.
Print total
First off, I think the line n = pow(n, 2) might be backwards from what you need. If you're converting binary digits, 2 is the base and n will be the power to raise it to, so you'll need n = pow(2, n).
Now, since you want to add up all the digits that are set to 1, you'll also need to add them to a new variable too. If you have more questions about this just ask here, and I'll see how I can help :)

round() function in python 2 and python 3 [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 4 years ago.
I'm solving some coding challenges on CoderByte and unfortunately they provide Python2. One thing I noticed is that the round() function is giving different outputs on python3 and python2. When i write this on python 2:
print int(round(100/60))
I get output of 1 (please explain why)
But on python 3 the same command gives 2 which is correct.
In python 2 the divide operator on integers returns integer, so 100/60==1. This unintuitive C-like behaviour was changed in python 3.
To make this code work properly in python 2 you should convert one of the integers to float: print int(round(100/60.)), that . means 60.0.
The problem is not the rounding, but the interpretation of /.
In python 2 if dividing 2 integers with / you get an integer not a float.
In python 3 you get a float if you use / - the "pure" integer division is done by using //.
Python 2:
print(100/60) # ==> 1
print(100/60.0) # ==> 1.6666666666...
Python 3:
print (100/60) # ==> 1.6666
print (100//60) # ==> 1
They both get rounded accordingly, but if you input a 1 into round, it will result in 1.
You can read more about the reason for the changed behaviour here: PEP 238
The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.
We propose to fix this by introducing different operators for different operations: x/y to return a reasonable approximation of the mathematical result of the division ("true division"), x//y to return the floor ("floor division"). We call the current, mixed meaning of x/y "classic division".

Write a recursive procedure that returns how many times digit C appers in number N? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do I write recursive procedure for this?
N is an integer, and C<10. A procedure must return how many times digit C appers in N
I won't give you the full answer, but I'll help you get oriented.
To write recursive functions you need to think of two parts.
Base case - What is the simplest possible case you could handle? For this problem, that could be when N is a 1-digit number.
Recursive case - Let's say you can handle N-digit numbers. How can you solve N+1-digit numbers, using your 1-digit function and your N-digit function? The answer is, carve off one digit. Feed that digit to the 1-digit checker and the other N digits to the N-digit checker. (The "N-digit checker" is the very function you're writing.)
In pseudo-code, a recursive function is typically structured like so:
def recursive_function(n):
if is_base_case:
return base_case(n)
else:
return combine(
recursive_function(smaller(n)),
base_case(bite_sized_chunk(n))
)
Your job is to fill in:
The is_base_case test: is n one digit?
The base_case function, which handles only 1-digit numbers.
The smaller function, which gives you all but the last digit of n. If n is 1234, smaller(n) is 123.
The bite_sized_chunk function, which gives you the last digit of n. If n is 1234, bite_sized_chunk is 4.
The combine function, which combines the base case and recursive answers.
(None of these functions need to be actual separate functions. They can be inlined.)

On significant figures of numbers in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary units depending on the study it comes from. Here is an example of what I mean:
[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2]
These are of course of type:
<type 'numpy.float64'>.
If I print out the last number, for instance:
print list[-1]
>>> 7.2
However, if accessed in this way, I get:
7.2000000000000002
I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:
[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]
Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?
You have three problems:
1) How do I determine the number of decimal places in the input?
If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.
If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:
for line in input_file:
data = [float(x) for x in line.split(',')]
You need to record the number of places to the right of the decimal before converting to float, for example:
for line in input_file:
places = [len(x.partition('.')[2]) for x in line.split(',')]
data = [float(x) for x in line.split(',')]
2) How do I store that information?
That's up to you. Sorry, I can't help you with that one without seeing your whole program.
3) How do I format the output to round to that number of decimal places?
Use the % operator or {}-style formatting, like so:
print '%.*f' % (places[i], data[i])

Categories