Division of Python Complex Numbers - python-3.x

I am trying to divide two complex numbers and not getting the desired result. How does division work for Python Complex numbers ?
Input values are: (2+3j) and (2+3j)
I have tried the below logic and this does not seem to work.
numerator_real = (real * conjugate.real) - (imag * conjugate.imag); // real
numerator_imag = (real * conjugate.imag) + (imag * conjugate.real); // imag
denom = x.real * x.real + x.imag * x.imag;
complex(numerator_real/denom, numerator_imag/denom)
Expected/Desired Result is: 1+0j
My output is 1.3+0j

Related

What is the most efficient way print first K digits of a factorial without calculating the whole factorial?

My K has to be around 15,
and the number of which i am tring to get first k of its factorial is ~10^9.
Essentially I need to compute first 15 digits of n! where <= 1000000000 in under a second or so.
Everyone says its easy in python but I am still not able to .
My attempt using Stirlings approximation is only printing first 4 digits correctly. Let alone efficiency. :'(
import * from decimal
import *from math
getcontext().prec = 100
n = int(input())
x = Decimal("10") ** Decimal(str(Decimal(str(n)) * Decimal(str(n)).log10() - Decimal(str(n)) * Decimal(e).log10()))
print(x * Decimal(Decimal("2") * Decimal(str(n)) * Decimal(pi)).sqrt())
Tried increasing precision of Decimal more but doesnt make any difference.

Divide by a number which is not power of 2 in Verilog RTL coding

For multiplication and division, we can use the left and right shifts.
x>>2 // it will right shift by 2. ---> 2^2=4. (Multiply by 4 or divide by 4, depends on MSB/LSB)
However, if we want to divide by a number that isn't the power of 2, how can we achieve the required purpose?
Booth's algorithm is an additive one and can take a comparatively longer time than the multiplicative algorithms, like the Newton-Raphson algorithms found in this educational PDF.
Each next approximation is calculated using the previous approximation.
X(N+1) = X(N)(2 - b * X(N)), where x(0)=1
So, to find the inverse of b, i.e. 1/b, where b=0.6 (error=e(x)), it takes about 5 iterations.
X(000) = 1.000
X(001) = 1.000 * (2 - (1.000 * 0.6)) = 1.400
X(002) = 1.400 * (2 - (1.400 * 0.6)) = 1.624
X(003) = 1.624 * (2 - (1.624 * 0.6)) = 1.6655744
X(004) = X(003) * (2 - (X(003) * 0.6)) = 1.666665951
X(005) = X(004) * (2 - (X(004) * 0.6)) = 1.666666668
which approximates the answer, which is 1.6666666667.
I included this example in case the referenced PDF disappears. See the referenced PDF or look up the Newton-Raphson algorithm for more information.
By using Booth's restoring division algorithm

Splitting an int64 into two int32, performing math, then re-joining

I am working within constraints of hardware that has 64bit integer limit. Does not support floating point. I am dealing with very large integers that I need to multiply and divide. When multiplying I encounter an overflow of the 64bits. I am prototyping a solution in python. This is what I have in my function:
upper = x >> 32 #x is cast as int64 before being passed to this function
lower = x & 0x00000000FFFFFFFF
temp_upper = upper * y // z #Dividing first is not an option, as this is not the actual equation I am working with. This is just to make sure in my testing I overflow unless I do the splitting.
temp_lower = lower * y // z
return temp_upper << 32 | lower
This works, somewhat, but I end up losing a lot of precision (my result is off by sometimes a few million). From looking at it, it appears that this is happening because of the division. If sufficient enough it shifts the upper to the right. Then when I shift it back into place I have a gap of zeroes.
Unfortunately this topic is very hard to google, since anything with upper/lower brings up results about rounding up/down. And anything about splitting ints returns results about splitting them into a char array. Anything about int arithmetic bring up basic algebra with integer math. Maybe I am just not good at googling. But can you guys give me some pointers on how to do this?
Splitting like this is just a thing I am trying, it doesnt have to be the solution. All I need to be able to do is to temporarily go over 64bit integer limit. The final result will be under 64bit (After the division part). I remember learning in college about splitting it up like this and then doing the math and re-combining. But unfortunately as I said I am having trouble finding anything online on how to do the actual math on it.
Lastly, my numbers are sometimes small. So I cant chop off the right bits. I need the results to basically be equivalent to if I used something like int128 or something.
I suppose a different way to look at this problem is this. Since I have no problem with splitting the int64, we can forget about that part. So then we can pretend that two int64's are being fed to me, one is upper and one is lower. I cant combine them, because they wont fit into a single int64. So I need to divide them first by Z. Combining step is easy. How do I do the division?
Thanks.
As I understand it, you want to perform (x*y)//z.
Your numbers x,y,z all fit on 64bits, except that you need 128 bits for intermediate x*y.
The problem you have is indeed related to division: you have
h * y = qh * z + rh
l * y = ql * z + rl
h * y << 32 + l*y = (qh<<32 + ql) * z + (rh<<32 + rl)
but nothing says that (rh<<32 + rl) < z, and in your case high bits of l*y overlap low bits of h * y, so you get the wrong quotient, off by potentially many units.
What you should do as second operation is rather:
rh<<32 + l * y = ql' * z + rl'
Then get the total quotient qh<<32 + ql'
But of course, you must care to avoid overflow when evaluating left operand...
Since you are splitting only one of the operands of x*y, I'll assume that the intermediate result always fits on 96 bits.
If that is correct, then your problem is to divide a 3 32bits limbs x*y by a 2 32bits limbs z.
It is thus like Burnigel - Ziegler divide and conquer algorithm for division.
The algorithm can be decomposed like this:
obtain the 3 limbs a2,a1,a0 of multiplication x*y by using karatsuba for example
split z into 2 limbs z1,z0
perform the div32( (a2,a1,a0) , (z1,z0) )
here is some pseudo code, only dealing with positive operands, and with no guaranty to be correct, but you get an idea of implementation:
p = 1<<32;
function (a1,a0) = split(a)
a1 = a >> 32;
a0 = a - (a1 * p);
function (a2,a1,a0) = mul22(x,y)
(x1,x0) = split(x) ;
(y1,y0) = split(y) ;
(h1,h0) = split(x1 * y1);
assert(h1 == 0); -- assume that results fits on 96 bits
(l1,l0) = split(x0 * y0);
(m1,m0) = split((x1 - x0) * (y0 - y1)); -- karatsuba trick
a0 = l0;
(carry,a1) = split( l1 + l0 + h0 + m0 );
a2 = l1 + m1 + h0 + carry;
function (q,r) = quorem(a,b)
q = a // b;
r = a - (b * q);
function (q1,q0,r0) = div21(a1,a0,b0)
(q1,r1) = quorem(a1,b0);
(q0,r0) = quorem( r1 * p + a0 , b0 );
(q1,q0) = split( q1 * p + q0 );
function q = div32(a2,a1,a0,b1,b0)
(q,r) = quorem(a2*p+a1,b1*p+b0);
q = q * p;
(a2,a1)=split(r);
if a2<b1
(q1,q0,r)=div21(a2,a1,b1);
assert(q1==0); -- since a2<b1...
else
q0=p-1;
r=(a2-b1)*p+a1+b1;
(d1,d0) = split(q0*b0);
r = (r-d1)*p + a0 - d0;
while(r < 0)
q = q - 1;
r = r + b1*p + b0;
function t=muldiv(x,y,z)
(a2,a1,a0) = mul22(x,y);
(z1,z0) = split(z);
if z1 == 0
(q2,q1,r1)=div21(a2,a1,z0);
assert(q2==0); -- otherwise result will not fit on 64 bits
t = q1*p + ( ( r1*p + a0 )//z0);
else
t = div32(a2,a1,a0,z1,z0);

How does the Pow() function work in Python in a mathematical equation?

Creating a mortgage Calculator, including 3 programmer-specified inputs (amount borrowed, interest rate, and 30 year payback period).
I am trying to turn this mathematical equation
(p * (1 + r)n * r) / ((1 + r)n - 1)
into code using variables, n will represent the squared user input
then I have to print out a summary of the all three inputs and the sum of the above equation.
First I imported math and tried the following
math.pow(an, 2)
int(pow(an, 2))
int(math.pow(an, 2))
Even when I tried without the pow function it wouldn't work
(amt * (1+per)an** * per)/((1+per)an** - 1)
Below is my current code:
import math
#input values
amt = input("Amount Borrowed:")
per = input("Annual interest rate:")
an = input("Payback period:")
#output values
mo = (amt * (1+per)pow(an, 2) * per)/((1+per)pow(an, 2) - 1)
#summary
print("Amount Borrowed: ", amt)
print("Annual Interest Rate:", per)
print("Total Years of Payments:", an)
print("Your monthly mortgage payment is: {mo:.2f}")
Example of expected results:
Amount borrowed (programmer input) = $270000
Annual interest rate (programmer input) = 5.125%
Payback period (programmer input) = 30 Years
Monthly payment (calculated output) = $1470.11
Errors:
mo = (amt * (1+per)pow(an, 2) * per)/((1+per)pow(an, 2) - 1)
SyntaxError: invalid syntax
mo = (amt * (1+per)an** * per)/((1+per)an** - 1)
SyntaxError: invalid syntax
You can't write a(b) to multiply a and b. Python syntax doesn't exactly match typical math syntax.
You're trying to do that when you write
(1+per)pow(an, 2)
You need to explicitly put a * in there if you want to multiply:
(1+per) * pow(an, 2)

calculate distance of two cities using Haversine formula-how to deal with minus longitudes

I'm going to find the distance between two cities using Haversine formula.
below is the code in VC++.
But I could't find the distance between the points (18.567367, -68.363431) and (33.636719,-84.428067) [first value is latitude, second is longitude].
It gives something like -1.#IND.
Could you please tell me how to deal with this issue?
below is the code:
double deg2rad(double deg) {
return (deg * pi / 180);
};
double TravelDistance(double lat1d, double lon1d, double lat2d, double lon2d) {
double lat1r, lon1r, lat2r, lon2r, u, v,dblDistance;
lat1r = deg2rad(lat1d);
lon1r = deg2rad(lon1d);
lat2r = deg2rad(lat2d);
lon2r = deg2rad(lon2d);
u = sin(lat2r - lat1r);
v = sin(lon2r - lon1r);
return ( 2.0 * earthRadiusKm * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v)))};
Thank in advance....!!
Looking at
http://en.wikipedia.org/wiki/Haversine_formula
it appears you have forgotten to divide by two in the arguments to sin() for u and v.
The answer you get is most likely because either the sqrt argument is < 0 or because the asin argument is > 1.

Resources