I wrote a code for finding the 'j' for the General Annuity
from __future__ import division
R = float(38973.76)
n = int(3)
r = int(8)
m = int(4)
mSubj = int(1)
t = int(3)
ans = ((1 + r / m) ** m)**(1 / mSubj) - 1
print(ans)
now the answer is 80.0
instead of 0.008243216 that I solved in Scientific Calculator.
Your R variable is the capital one, not r.
so it should be ans = ((1 + R / m) ** m)**(1 / mSubj) - 1
Related
I tried to solve a recurrence relation.
$$
\def\r #1{\langle r^{#1} \rangle}
0 = 8 n E \r{n - 1}
+ (n - 1)[n(n - 2) - 4l(l + 1)] \r{n - 3}
+ 4(2n - 1) \r{n - 2}
$$
This equation is from quantum mechanics. It derived from the Hamitonian with Coloumb potential.
$$
H = \frac{1}{2} p^2_r
+ \frac{l(l + 1)}{2 r^2}
- \frac{1}{r}
$$
E and l are symbols, <r^n> is the expected value of r^n repect to the energy eigenstate.
I have a Sage script using SymPy to solve the recurrence relation. My goal is to express <r^n> as a function of E and l. Here is my script.
import sympy
from sympy import Function, rsolve
from sympy.abc import n
l = sympy.symbols('l',integer=True)
energy = sympy.symbols('E')
r = Function('r')
f = 8 * n * energy * r(n - 1) \
+ 4 * (2 * n - 1) * r(n - 2) \
+ (n - 1) * (n * (n - 2) - 4 * l * (l + 1)) * r(n - 3)
print(rsolve(f, r(n), {r(0): 1}))
I don't know why the output result is None. I have tried to set l and energy to explicit interger, for example, 1. But it didn't help.
Expected result
I am sorry. I don't know. The recurrence relation is too hard for my brain. I am not good at math.
Output from print
There is no error, and below is the output.
None
Extra question
If my recurrence relation doesn't have a general solution, is it possible to get the results of specific r(n), for example r(10)?
Reply for my extra question
I figured out the recursive method to generate the result of specific r(n).
from functools import cache
#cache
def expected_distance(n, l):
if n <= -2:
return 0
if n == -1:
return -2 * energy
if n == 0:
return 1
return simplify((
- 4 * (2 * (n + 1) - 1) * expected_distance(n - 1, l) \
- n * ((n + 1) * (n - 1) - 4 * l * (l + 1)) * expected_distance(n - 2, l)
) / (8 * (n + 1) * energy))
So I have tried the same math in c# and python but got 2 different answer. can someone please explain why is this happening.
def test():
l = 50
r = 3
gg= l + (r - l) / 2
mid = l + (r - l) // 2
print(mid)
print(gg)
public void test()
{
var l = 50;
var r = 3;
var gg = l + (r - l) / 2;
double x = l + (r - l) / 2;
var mid = Math.Floor(x);
Console.WriteLine(mid);
Console.WriteLine(gg);
}
In C#, the / operator performs integer division (ignores the fractional part) when both values are type int. For example, 3 / 2 = 1, since the fractional part (0.5) is dropped.
As a result, in your equation, the operation (r - l) / 2 is evaluating to -23, since (3 - 50) / 2 = -47 / 2 = -23 (again, the fractional part is dropped). Then, 50 + (-23) = 27.
However, Python does not do this. By default, all division, whether between integers or doubles, is "normal" division - the fractional part is kept. Because of that, the result is the same as you'd get on a calculator: 50 + (3 - 50) / 2 = 26.5
If you want C# to calculate this the same way as Python, the easiest way is to make one of the numbers a double. Adding .0 to the end of the divisor should do the trick:
// changed '2' to '2.0'
var gg = l + (r - l) / 2.0;
double x = l + (r - l) / 2.0;
26
26.5
import sys
t=(int(sys.stdin.readline()))
for i in range(0,t):
n=int(sys.stdin.readline())
c=0
s=n*(n+1)/2
if s%2!=0:
print(0)
else:
c=0
i=-1
a=[i for i in range(1,n+1)]
h=s//2
m=0
s1=0
for i in range(n-1,-1,-1):
s1+=a[i]
c+=1
if s1==h:
m=1
break
if s1>h:
break
if m==1:
s1=((c+1)*(2+((c-1)-1)))//2+((n-c-1)*(2+((n-c-1)-1)))//2
print(s1)
else:
print(c)
I am new to python , How can i write this code with using for loop? i don't want to use for loop because i get TLE error. Thanks in advance
Here is the question :
N. Consider the sequence sequence=(1,2,…,N). You should choose two elements of this sequence and swap them.
A swap is perfect if there is an integer o (1≤o<N) such that the sum of the first M elements of the resulting sequence is equal to the sum of its last N−o elements. Find the number of perfect swaps.
i got interested in the problem and found this so far:
a slow version that creates list and really does swap elements is this:
from itertools import combinations
def slow(N):
found = 0
for i, j in combinations(range(N), 2):
lst = list(range(1, N + 1))
lst[i], lst[j] = lst[j], lst[i]
for m in range(1, N):
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
assert a == sum(lst[:m])
assert b == sum(lst[m:])
if sum(lst[:m]) == sum(lst[m:]):
found += 1
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
else:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j != N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) != N * (N + 1)
return found
as you see i found criteria the indices have to fulfill in order for the sum to be correct:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
i also found the direct formula to calculate the sum up to m and the one starting from m:
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
all of that can can be calculated using some basic mathematics.
starting from that you can do some more maths and see that there are 2 cases to consider:
there is an m such that the sum of the original list [1, 2, 3, ..., m, m+1, ..., N] up to m equals the sum of the rest of the list (e.g. N = 20; m = 14). two cases again:
all the swaps that do not cross the m boundary are valid (there are comb(m, 2) + comb((N - m), 2)) of them.
when you split at m-1 you will find more swaps; this time you have to swap accross the m-1 boundary.
the m in that case is calculated from
m = - 1 + sqrt(1 + 2 * N * (N + 1)) / 2
the calculation for m in the first case is not an integer (i.e. 1 + 2 * N * (N + 1) is not a perfect square). the m to consider is then then the floor of the result of the formula above (i use int instead of math.floor). two cases again for the difference of the sum of the two splits:
the difference is even: there are more swaps that need to go over the m boundary.
the difference is odd: no additional swaps (swapping will always result in an even difference)
this is the code:
from math import sqrt, comb
def fast(N):
found = 0
arg = (1 + 2 * N * (N + 1))
sq = round(sqrt(arg))
if sq ** 2 == arg and sq & 1:
m = (-1 + sq) // 2
found += comb(m, 2) + comb((N - m), 2)
m -= 1
found += N - m - 1
else:
m = int((-1 + sqrt(arg)) // 2)
diff = ((m + 1 + N) * (N - m) - m * (m + 1)) // 2
if diff & 1 == 0:
found += N - m
return found
I try Montgomery Multiplication Algorithm on Python 3.x. This algorithm pseudo-code is given below:
Input: Modulus N(n bit), gcd(n, 2) = 1, Multipler: A (n bit), Multiplicant: B (n bit)
Output: R = (A x B x 2 ^ (-n)) mod N
R = 0
for (i = 0; i < n; i++)
{
q = (R + A(i) * B) mod 2
R = (R + A(i) * B + q * N) / 2
}
print(R)
Python 3.x code that was written is given below:
#!/usr/bin/python3
N = 41
A = 13
B = 17
n = N.bit_length()
R = 0
for i in range(0, n):
q = int(R + (A & (1 << i) != 0) * B) % 2
R = int((R + (A & (1 << i) != 0) * B + q * N) / 2)
print("Result:", R % N)
But, the code isn't given correct result. What is the problem?
Thanks for answering.
When I run your (modified) code I get 31, and 31 appears to be the right answer.
According to your pseudocode, R should be
R = (A x B x 2 ^ (-n)) mod N
In your case that is
R = (13*17*2^(-6))%41
The interpretation of 2^(-6) when you are working mod 41 is to raise the mod 41 multiplicative inverse of 2 to the power 6, then take the result mod 41. In other words, 2^-6 = (2^-1)^6.
Since 2*21 = 42 = 1 (mod 41), 2^(-1) = 21 (mod 41). Thus:
R = (13*17*2^-6) (mod 41)
= (13*17*(2^-1)^6) (mod 41)
= (13*14*21^6) (mod 41)
= 18954312741 (mod 41)
= 31
which shows that the result is 31, the number returned by your code.
Thus your code is correct. If there is a clash between output and expectation, perhaps in this case the problem is one of expectation.
Python keeps telling me invalid syntax
In [7]: File "/tmp/ipython-4302iuN.py", line 26
for n in N:
^
SyntaxError: invalid syntax
The reason it occurs on line 26 and I don't have 26 lines here is due to the shebang line and comments.
L = 80.0
N = 2 ** np.arange(0, 10, dtype = np.float64)
dt = 0.0002
tmax = 10
nmax = int(np.floor(tmax / dt)) # also try ceil/floor
deltax = []
error = []
u = 2. * (2. / (np.exp(x + 20.) + np.exp(-x - 20.)) ** 2
for n in N:
dx = L / n
I have tried using range with integers as a test. I opened a separate ipython and ran
for n in range(1, 2):
dx = 10 / n
which worked just fine.
What is wrong with the syntax?
I have closed python and re-opened but that didn't help either.
When faced with a mysterious syntax error, always look above:
>>> s = "u = 2. * (2. / (np.exp(x + 20.) + np.exp(-x - 20.)) ** 2"
>>> s.count("(")
4
>>> s.count(")")
3
You forgot to add an ending bracket here
u = 2. * (2. / (np.exp(x + 20.) + np.exp(-x - 20.)) ** 2)
^
On top of that you have not defined x here:
u = 2. * (2. / (np.exp(x + 20.) + np.exp(-x - 20.)) ** 2)