Need integer output from equation using complex numbers in python - python

I have some equation for a type of step function which I obtained with wolfram alpha:
a_n = 1/8 (2 n+(-1)^n-(1+i) (-i)^n-(1-i) i^n+9)
Using in wolfram with any positive integer will yield me a positive integer result however when I try the following in python
import numpy as np
n = 5
i = complex(0,1)
a = (1/8)*((2*n)+(np.power(-1,n))-(1+i)*(np.power(-i,n))-(1-i)*(np.power(i,n))+9)
I'm always stuck with some real + imaginary part. I need to be able to obtain an integer output for a for use in other equations.

Maybe you want int(a.real) at the end.
Also be aware that by default 1/8 will be evaluated as 0 in Python 2.x

(1+i) (-i)^n+(1-i) i^n
is two times the real part of (1-i) i^n which is, for instance
2*cos(pi/2*n)-2*cos(pi/2*(n+1))
or as values
n 0 1 2 3 4 5 6 7 8
expression 2 2 -2 -2 2 2 -2 -2 2
this is subtracted from the alternating sequence to give
n 0 1 2 3 4 5 6 7 8
(-1)^n-expr -1 -3 3 1 -1 -3 3 1 -1
periodically with period 4
This can be computed avoiding all powers and saveguarding for negative n as
3-2*(((n+2) mod 4 +4) mod 4)
adding 2n+9 to complete the expression gives
12+2*n-2*(((n+2) mod 4 +4) mod 4)
which is indeed divisible by 8, so
a = 1+(n+2-(((n+2) % 4 +4) % 4) )/4
now if one considers that this just reduces (n+2) to the next lower multiple of 4, this is equivalent to the simplified
a = 1 + (n+2)/4
using integer division.

Related

How to find 2 to the power of an insanely big number modulo 10^9

I have an excessively big number (1500+) digits and I need to find 2 ** that number modulo 1_000_000_000 so I wrote this python:
n = 1
return_value = 2
while n < To_the_power_of:
return_value *= 2
return_value = return_value % 1_000_000_000
n += 1
This returns the correct value for smaller values, but takes too long for bigger values.
If the number is modulo 10 then you get this pattern which could be used.
2 ** 1 modulo 10 = 2
2 ** 2 modulo 10 = 4
2 ** 3 modulo 10 = 8
2 ** 4 modulo 10 = 6
2 ** 5 modulo 10 = 2
2 ** 6 modulo 10 = 4
2 ** 7 modulo 10 = 8
2 ** 8 modulo 10 = 6
I'm hoping that a similar pattern could be used to answer the original problem.
You already know that the sequence will repeat. You found the cycle of 4 for mod 10; now, just find it for a billion:
mod_billion = set()
pow_2 = 2
billion = 10**9
while pow_2 not in mod_billion:
mod_billion.add(pow_2)
pow_2 *= 2
if pow_2 > billion:
pow_2 -= billion
print (pow_2, len(mod_billion))
Three seconds later, we get:
512 1562508
Thus, this sequence repeats every 1562508 items. To find your value for your given power:
cycle = 1562508
small_power = big_power % cycle
result = (2 ** small_power) % billion
Your code makes about 10 ** 1500 iterations, which is indeed insanely long. A useful general technique is exponentiation by squaring, which will give you the result in about 4500 iterations.
If you want to follow the path of the #Prune's answer, you should go along the lines of Fermat's Little Theorem, specifically the Euler's generalization. phi(1_000_000_000) is easy to compute, because 10 ** 9 = (2 ** 9) * (5 ** 9), the product of 2 powers of primes.

In Python Dictionaries, how does ( (j*5)+1 ) % 2**i cycle through all 2**i

I am researching how python implements dictionaries. One of the equations in the python dictionary implementation relates the pseudo random probing for an empty dictionary slot using the equation
j = ((j*5) + 1) % 2**i
which is explained here.
I have read this question, How are Python's Built In Dictionaries Implemented?, and basically understand how dictionaries are implemented.
What I don't understand is why/how the equation:
j = ((j*5) + 1) % 2**i
cycles through all the remainders of 2**i. For instance, if i = 3 for a total starting size of 8. j goes through the cycle:
0
1
6
7
4
5
2
3
0
if the starting size is 16, it would go through the cycle:
0 1 6 15 12 13 2 11 8 9 14 7 4 5 10 3 0
This is very useful for probing all the slots in the dictionary. But why does it work ? Why does j = ((j*5)+1) work but not j = ((j*6)+1) or j = ((j*3)+1) both of which get stuck in smaller cycles.
I am hoping to get a more intuitive understanding of this than the equation just works and that's why they used it.
This is the same principle that pseudo-random number generators use, as Jasper hinted at, namely linear congruential generators. A linear congruential generator is a sequence that follows the relationship X_(n+1) = (a * X_n + c) mod m. From the wiki page,
The period of a general LCG is at most m, and for some choices of factor a much less than that. The LCG will have a full period for all seed values if and only if:
m and c are relatively prime.
a - 1 is divisible by all prime factors of m.
a - 1 is divisible by 4 if m is divisible by 4.
It's clear to see that 5 is the smallest a to satisfy these requirements, namely
2^i and 1 are relatively prime.
4 is divisible by 2.
4 is divisible by 4.
Also interestingly, 5 is not the only number that satisfies these conditions. 9 will also work. Taking m to be 16, using j=(9*j+1)%16 yields
0 1 10 11 4 5 14 15 8 9 2 3 12 13 6 7
The proof for these three conditions can be found in the original Hull-Dobell paper on page 5, along with a bunch of other PRNG-related theorems that also may be of interest.

How do you triangulate a number in python?

I have to do these for school and I don't know how to.
Write a function print_triangular_numbers(n) that prints out the first n triangular numbers (n is an input). A call to print_triangular_numbers(5) would produce the following output:
n result
1 1
2 3
3 6
4 10
5 15
A triangular number can be expressed as
n(n+1)/2
Thus, you need to build a simple loop, starting at 1 and going through your passed parameter:
def print_triangular_numbers(n):
for x in range(1,n+1):
print x, x * (x + 1) / 2
The for loop starts at 1 and goes through n+1 because range is not inclusive of the end point.
This outputs:
1 1
2 3
3 6
4 10
5 15

How python calculate this modulo? [duplicate]

This question already has answers here:
How does the modulo (%) operator work on negative numbers in Python?
(12 answers)
Closed 4 months ago.
How python calculate mathematically this modulo?
>>>-1%10
9
The Wikipedia article on the modulo operation provides the following constraint for a % q:
a = nq + r
Substituting a = -1, q = 10 and r = 9, we see that n must be equal -1.
Plugging in -1 for n:
-1 % 10 # Python evaluates this as 9
-1 = n * 10 + r
-1 = -1 * 10 + r
9 = r
Testing with another example (again plugging in -1 for n):
-7 % 17 # Python evaluates this as 10
-7 = n * 17 + r
-7 = -17 + r
10 = r
A third example with a positive numerator and negative denominator:
7 % -17 # Python evaluates this as -10
7 = n * (-17) + r
7 = -1 * (-17) + r
7 = 17 + r
-10 = r
It appears that when a and q have different signs, we start with n = -1 and decrement n by 1 until we've found the n closest to zero such that n*q < a. We can test this by trying this out with an a and q such that |a| > |q|:
-100 % 11 # Python evaluates as 10
-100 = n * 11 + r
... -1 # -11 > -100
... -2 # -22 > -100
... -3 ...
... -4 ...
... -5 ...
... -6 ...
... -7 ...
... -8 ...
... -9 # -99 > -100
-100 = -10 * 11 + r # -110 < -100
-100 = -110 + r
10 = r
So while this might not be the algorithm Python actually uses to calculate the modulo, we at least have a useful mental model for reasoning about how a given result was arrived at.
Its is caluclated like this :-
-10 / 10 = -1 ,
hence remainder 9.
-10 is greatest multiple of 10 which is less than -1.
It is similar to 9 % 5 , will be greatest number less than dividend should be considers.
5/5 = 1 , hence 4.
I'm not sure if you're asking the algorithm that python uses, or why the answer comes out this way.
If the latter, imagine that for modulo n you subtract or add n until you get a number between 0 and n-1 inclusive
For at least python-2.7.9 it is done by first doing the integer division x/y with truncation towards zero. Then the difference of x and the quotient multiplied by y (ie x - (x/y)*y) is calculated. If the result is nonzero and y is of different sign then y is added to the result.
For example with your example x=-1 and y=10, we first calculate x/y which is 0 (-0.1 rounds to 0). The difference then is -1 - 0 which is -1. Now -1 is non-zero and with different sign than 10, so we add 10 to it and get 9.
For python3 (3.4.2) it's a bit more complicated as by python3 the integers are actually longs so the division algorithm is implemented in software rather than hardware, but otherwise basically the same. The division is done as unsigned division using the normal division algorithm using base 2^N for some suitable number N depending on platform.

Arithmetic in python, can't figure out simple basic operations

I am doing some very basic excersizes in python. I'm using the hard way to learn python book, which in excersize 3 have a expression I should understand.
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6, is coming out as 7.
For me, the answer is 6.
6 - 5 + 0 - 1 / 4 + 6
1 - 1 / 4 + 6
6.
This is clearly wrong, but can anyone help me with priorty in mathematics etcetera? I seem to have forgotten everything if it's not inside a parenthesis!
EDIT: Thank you very much for the response. I've clearly learned something about the very basic stuff, which I think is important before moving on! My order of operations was definately way off!
4 % 2 = 0 because the remainder of 4 / 2 is 0
1 / 4 is also 0 because it is doing integer division and .25 is floored to 0.
If we look at the rules for Operator precedence in Python we can see that:
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
is being treated as:
3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6
(For the arithmetic operators this is the same order as the standard order of operations in mathematics.)
Now 4 % 2 is 0 since the remainder when dividing 4 by 2 is 0. 1 / 4 is also 0 as Python will return a value of the same type as the operands and 0.25 when "floored" is 0.
So I think your mistake is applying the / to the whole expression to the left. In fact as / has a higher precedence than - the division evaluated is 1 / 4.
See the table of operator precedences in Python.
http://docs.python.org/reference/expressions.html#summary
1/4 rounds down (or floors) to 0 since 1 and 4 are integers.
Therefore 1-0+6 = 7
You seem to think that python should evaluate everything to the left of a / operator before dividing by the first token to the right. That would be an odd evaluation order by any measure.
As always with programming: if you have a complex expression with infix operators, use brackets to force the correct order.
In Python3.x it'd be 6.75 b/c 1/4 = 0.25 (true division). However, in Python 2.x 1/4 = 0 (convert to the most generic type of the arguments used, that is int in given case). Therefore, if it'd be 1. / 4 or 1 / 4. then in Python2.x you'd get 0.25 and the result would be 6.75
Priority is for division and multiplication, if you don't use brackets!
In this way: 1-1/4+6=7 because 1/4, working with integer, is = 0
operands are integer, so 1/4 integer dividing = 0
Rather than mathematics you should have a look at the operators:
a%b is a modular b, which in case of a=4 and b=2 yields 0 (ok, thanks mathematics ;) )
1/4: here it's important to take into account that 1 and 4 are integers. So the result will also be an integer, i.e. 0.25 becomes 0.
That's why you end up with
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
= 3 + 2 + 1 - 5 + 0 - 0 + 6
= 7
For operators in python have a look at the python docs.
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
The order of precedence for this is multiplication and division evaluated left to right and then addition and subtraction. So..
3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6
The ones inside the parentheses are evaluated first because of order of operations. Because you only have integers present (and not a float which would allow the value 0.25), 1/4 will floor to 0 because of python.
3 + 2 + 1 - 5 + 0 - 0 + 6
Afterwards, when you evaluate from left to right for addition/subtraction, you are left with:
6 - 5 + 6 => 1 + 6 => 7
Remember that division and multiplication are evaluated before addition and subtraction. For more information, Order of Operations - Wikipedia

Categories