Order of Operation Mathematical - python-3.x

new to programming and came across this while doing a worksheet:
x = 1 / 2 + 3 // 3 + 4 ** 2
what is x?
I read that in regards to the exponent you have to read it right to left, and I did that and I keep getting 0 for some reason even though the answer was supposed to be 17.5. Any help on why/how I am supposed to get 17.5 and the order I was supposed to work it out from would be greatly appreciated. thanks.

Using Python, the result is 17.5
You can check the order of the mathematical operators in python (Python Operator Precedence) for more information
(1 / 2) + (3 // 3) + (4 ** 2) = 0.5 + 1 + 16
Ref:
https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html

To determine the order of precedence for this expression, keep in mind these rules (non-exhaustive):
evaluation goes from left to right
Multiplication/division has higher precedence than addition/subtraction (e.g. 1 + 2 / 3 gets evaluated as 1 + (2 / 3))
Exponent/power has higher precedence than multiplication and division (e.g. 1 / 2**4 gets evaluated as 1 / (2**4))
These rules together show us that this expression:
x = 1 / 2 + 3 // 3 + 4 ** 2
Will be evaluated as:
x = (1 / 2) + (3 // 3) + (4 ** 2)
Therefore, x = 0.5 + 1 + 16 = 17.5.

The operator precedence is defined in the Python documentation:
https://docs.python.org/3/reference/expressions.html#operator-precedence
So, ** has the highest precedence, then / and // and then +.

Related

How to prove fraction addition in dafny

I want to prove the following about fraction addition. Namely j/2+k/2 = (j+k)/2. To do so, I have the following below:
lemma adding_fraction(j: nat, k: nat)
ensures j / 2 + k / 2 == (j + k) / 2
{
assert j / 2 + k / 2
== j * (1 / 2) + k * (1 / 2)
== (1/2) * (j + k)
== (j + k) / 2
assert j/2 + k/2 == (j + k) / 2;
}
I get an invalid AssertStmt error on the last like of this lemma. I'm not entirely sure why. Moreover I'm not sure why dafny is unable to prove this about addition already. Could someone provide some assistance on how I can prove this lemma?
I see one error actually now. Namely in dafny 1/2 == 0 is true. So all division seems to be done with a floor operation. That said in the code above is j%2=0 and k%2=0 then dafny's able to prove it no problem. How can I force dafny not to use floor? This is an issue since in real life: 1/2 + 5/2 = 6/2 = 3 but in dafny with floor: 1/2 + 5/2 = 0 + 2 = 2.
First, the lemma is not true. If j and k are both odd, then j / 2 + k / 2 will be one less than (j + k) / 2 because division is truncating integer division. For example, we can prove the following counterexample in Dafny
lemma counterexample()
ensures var j := 1; var k := 3;
!(j / 2 + k / 2 == (j + k) / 2)
{}
As to your other question, you are missing a semicolon on the second to last line. Dafny's error message could be improved here, but it's good to keep in mind in the future that any time Dafny reports an "invalid ", it's a syntax error and you should be on the lookout for typos. The full Dafny message for this error is (roughly)
tmp.dfy(8,4): Error: invalid AssertStmt
1 parse errors detected in tmp.dfy
You can see that it at least contains a line number (for the assertion after the missing semicolon) and the phrase "parse errors" on the second line of the error message.
After fixing this syntax error, there are several semantic errors having to do with not being able to prove the assertions. The underlying cause for these is that the lemma is false.

Create a Recursive Function as Well as a Closed Function Definition

The goal of this assignment is to take the recurrence relation given at the bottom, and then create a recursive function under recFunc(n), as well as a closed function definition underneath nonRecFunc(n). A closed function means our function should solely depend on n, and that its output should
match the recursive function's exactly. Then, find the value for n = 15 and n = 20, and use it as instructed below. You should probably need to use a characteristic equation to solve this problem.
What is the value for nonRecFunc(20) (divided by) nonRecFunc(15), rounded to the nearest integer.
Problem:
Solve the recurrence relation a_n = 12a_n-1 - 32a_n-2 with initial conditions a_0 = 1 and a_1 = 4.
I am confused as to how I should attack this problem and how I can use recursion to solve the issue.
def recFunc(n):
if n == 0:
return 1
elif n == 1:
return 2
else:
return recFunc(n - 1) + 6 * recFunc(n - 2)
def nonRecFunc(n):
return 4/5 * 3 ** n + 1/5 * (-2) ** n
for i in range(0,10):
print(recFunc(i))
print(nonRecFunc(i))
print()
As mentioned in a my comment above, I leave the recursive solution to you.
For the more mathematical question of the non-recursive solution consider this:
you have
x_n = a x_(n-1) + b x_(n-2)
This means that the change of x is more or less proportional to x as x_n and x_(n-1) will be of same order of magnitude. In other words we are looking for a function type giving
df(n)/dn ~ f(n)
This is something exponential. So the above assumption is
x_n = alpha t^n + beta s^n
(later when solving for s and t the motivation for this becomes clear) from the start values we get
alpha + beta = 1
and
alpha t + beta s = 2
The recursion provides
alpha t^n + beta s^n = a ( alpa t^(n-1) + beta s^(n-1) ) + b ( alpa t^(n-2) + beta s^(n-2) )
or
t^2 alpha t^(n-2) + s^2 beta s^(n-2) = a ( t alpa t^(n-2) + s beta s^(n-2) ) + b ( alpa t^(n-2) + beta s^(n-2) )
This equation holds for all n such that you can derive an equation for t and s.
Plugging in the results in the above equations gives you the non-recursive solution.
Try to reproduce it and then go for the actual task.
Cheers.

Haskell big number calculations

I am trying to do some calculations with big numbers
λ: let r = 291381631919914084
λ: let t = 1165526527679656343
λ: sqrt(4 * r * r - 4 * r + 1 + 8 * t) - 2 * r + 1
1.0
the answer should be 8.0000...
Is there a package that I should be using for such calculations? or is there something I should be doing in prelude?
The correct answer is indeed very close to 8.0. You're running into numerical precision issues: the square root is being computed using IEEE 754 ("double precision") binary64 format, and its 53-bit precision isn't sufficient to give an accurate result here.
In more detail: the true value of sqrt(4 * r * r - 4 * r + 1 + 8 * t) is, to 50 significant figures:
582763263839828175.00000000000000000686385063746811
The closest representable IEEE 754 binary64 value to that quantity is:
582763263839828224.0
... which is off by about 49.0 from the true value. Similarly, the value 2*r loses precision when converted to floating-point.
You might be tempted to fix this by increasing the precision, but as so often happens in numerical work, in this case it's better to rework the algorithm to avoid (or at least ameliorate) the numerical issues. The value you're computing is of the form sqrt(a * a + b) - a (with a = 2 * r - 1 and b = 8 * t). That quantity can be rewritten in the form b / (sqrt(a * a + b) + a), and (assuming that both a and b are positive), the latter expression will give a more accurate result.
Here's a quick demonstration that the two expressions give the same result.
Prelude> let a = 43
Prelude> let b = 7
Prelude> sqrt(a * a + b) - a
8.131845707602992e-2
Prelude> b / (sqrt(a * a + b) + a)
8.131845707603225e-2
We're using smaller values of a and b, so the numerical issues aren't so bad, but note that there's still a discrepancy in the last 4 digits. (The exact value here is 0.081318457076032250005683932322636450, to 35 significant figures.)
And using this form of the expression with your values:
Prelude> let r = 291381631919914084
Prelude> let t = 1165526527679656343
Prelude> let a = 2*r - 1; b = 8*t in b / (sqrt(a*a+b) + a)
8.0
As other answerers have pointed out, the answer isn't exactly 8.0, but 8.0 is the closest IEEE 754 binary64 floating-point value to the true answer.
I believe 8 is not a correct answer, either; the number you have given is not square:
Math.NumberTheory.Powers.Squares> r = 291381631919914084
Math.NumberTheory.Powers.Squares> t = 1165526527679656343
Math.NumberTheory.Powers.Squares> isSquare (4*r*r - 4*r + 1 + 8*t)
False
However, you can get this answer if it's the one you want:
Math.NumberTheory.Powers.Squares> integerSquareRoot (4*r*r - 4*r + 1 + 8*t) - 2*r + 1
8
The arithmoi package provides these functions.
Or, you can get as many digits of the exact answer as you like:
Data.Number.CReal> sqrt (4*r*r - 4*r + 1 + 8*t) - 2*r + 1 :: CReal
8.0000000000000000068638506374681082902485
The numbers package provides this type.
I put these numbers and formula in Rstudio and also got 1. Are you sure the answer is 8? Maybe add more parentheses to make sure you got your order of operation correct.

Change-making: Dynamic Programming

In a lecture earlier, we were told that using a greedy approach to solve a change making problem would not always work.
An example of this was given as follows:
We want to reach n = 14, and we have three coins of different values: d1 = 1,d2 = 7,d3 = 10.
Using the greedy approach this would lead us to do 10 + 1 + 1 + 1 + 1 (5 coins).
It was said the a dynamic problem approach would solve this accurately. I tried working it out but it came back to 5.
Assume F holds the number of coins needed to make an amount
F[14] = min {F[14 – 1] , F[14 – 7], F[14 – 10]} + 1
= F[14 – 10] + 1 = 4 + 1 = 5
This shows again that we need 5 coins, when this can clearly be done by using 2 coins (7 + 7).
What gives? Thanks.
You assumed that min {F[14 – 1] , F[14 – 7], F[14 – 10]}=F[14-10] when it is not the case. The minimum is actually F[14-7]=1 and hence the optimum is 2

Count the Number of Zero's between Range of integers

. Is there any Direct formula or System to find out the Numbers of Zero's between a Distinct Range ... Let two Integer M & N are given . if I have to find out the total number of zero's between this Range then what should I have to do ?
Let M = 1234567890 & N = 2345678901
And answer is : 987654304
Thanks in advance .
Reexamining the Problem
Here is a simple solution in Ruby, which inspects each integer from the interval [m,n], determines the string of its digits in the standard base 10 positional system, and counts the occuring 0 digits:
def brute_force(m, n)
if m > n
return 0
end
z = 0
m.upto(n) do |k|
z += k.to_s.count('0')
end
z
end
If you run it in an interactive Ruby shell you will get
irb> brute_force(1,100)
=> 11
which is fine. However using the interval bounds from the example in the question
m = 1234567890
n = 2345678901
you will recognize that this will take considerable time. On my machine it does need more than a couple of seconds, I had to cancel it so far.
So the real question is not only to come up with the correct zero counts but to do it faster than the above brute force solution.
Complexity: Running Time
The brute force solution needs to perform n-m+1 times searching the base 10 string for the number k, which is of length floor(log_10(k))+1, so it will not use more than
O(n (log(n)+1))
string digit accesses. The slow example had an n of roughly n = 10^9.
Reducing Complexity
Yiming Rong's answer is a first attempt to reduce the complexity of the problem.
If the function for calculating the number of zeros regarding the interval [m,n] is F(m,n), then it has the property
F(m,n) = F(1,n) - F(1,m-1)
so that it suffices to look for a most likely simpler function G with the property
G(n) = F(1,n).
Divide and Conquer
Coming up with a closed formula for the function G is not that easy. E.g.
the interval [1,1000] contains 192 zeros, but the interval [1001,2000] contains 300 zeros, because a case like k = 99 in the first interval would correspond to k = 1099 in the second interval, which yields another zero digit to count. k=7 would show up as 1007, yielding two more zeros.
What one can try is to express the solution for some problem instance in terms of solutions to simpler problem instances. This strategy is called divide and conquer in computer science. It works if at some complexity level it is possible to solve the problem instance and if one can deduce the solution of a more complex problem from the solutions of the simpler ones. This naturally leads to a recursive formulation.
E.g. we can formulate a solution for a restricted version of G, which is only working for some of the arguments. We call it g and it is defined for 9, 99, 999, etc. and will be equal to G for these arguments.
It can be calculated using this recursive function:
# zeros for 1..n, where n = (10^k)-1: 0, 9, 99, 999, ..
def g(n)
if n <= 9
return 0
end
n2 = (n - 9) / 10
return 10 * g(n2) + n2
end
Note that this function is much faster than the brute force method: To count the zeros in the interval [1, 10^9-1], which is comparable to the m from the question, it just needs 9 calls, its complexity is
O(log(n))
Again note that this g is not defined for arbitrary n, only for n = (10^k)-1.
Derivation of g
It starts with finding the recursive definition of the function h(n),
which counts zeros in the numbers from 1 to n = (10^k) - 1, if the decimal representation has leading zeros.
Example: h(999) counts the zero digits for the number representations:
001..009
010..099
100..999
The result would be h(999) = 297.
Using k = floor(log10(n+1)), k2 = k - 1, n2 = (10^k2) - 1 = (n-9)/10 the function h turns out to be
h(n) = 9 [k2 + h(n2)] + h(n2) + n2 = 9 k2 + 10 h(n2) + n2
with the initial condition h(0) = 0. It allows to formulate g as
g(n) = 9 [k2 + h(n2)] + g(n2)
with the intital condition g(0) = 0.
From these two definitions we can define the difference d between h and g as well, again as a recursive function:
d(n) = h(n) - g(n) = h(n2) - g(n2) + n2 = d(n2) + n2
with the initial condition d(0) = 0. Trying some examples leads to a geometric series, e.g. d(9999) = d(999) + 999 = d(99) + 99 + 999 = d(9) + 9 + 99 + 999 = 0 + 9 + 99 + 999 = (10^0)-1 + (10^1)-1 + (10^2)-1 + (10^3)-1 = (10^4 - 1)/(10-1) - 4. This gives the closed form
d(n) = n/9 - k
This allows us to express g in terms of g only:
g(n) = 9 [k2 + h(n2)] + g(n2) = 9 [k2 + g(n2) + d(n2)] + g(n2) = 9 k2 + 9 d(n2) + 10 g(n2) = 9 k2 + n2 - 9 k2 + 10 g(n2) = 10 g(n2) + n2
Derivation of G
Using the above definitions and naming the k digits of the representation q_k, q_k2, .., q2, q1 we first extend h into H:
H(q_k q_k2..q_1) = q_k [k2 + h(n2)] + r (k2-kr) + H(q_kr..q_1) + n2
with initial condition H(q_1) = 0 for q_1 <= 9.
Note the additional definition r = q_kr..q_1. To understand why it is needed look at the example H(901), where the next level call to H is H(1), which means that the digit string length shrinks from k=3 to kr=1, needing an additional padding with r (k2-kr) zero digits.
Using this, we can extend g to G as well:
G(q_k q_k2..q_1) = (q_k-1) [k2 + h(n2)] + k2 + r (k2-kr) + H(q_kr..q_1) + g(n2)
with initial condition G(q_1) = 0 for q_1 <= 9.
Note: It is likely that one can simplify the above expressions like in case of g above. E.g. trying to express G just in terms of G and not using h and H. I might do this in the future. The above is already enough to implement a fast zero calculation.
Test Result
recursive(1234567890, 2345678901) =
987654304
expected:
987654304
success
See the source and log for details.
Update: I changed the source and log according to the more detailed problem description from that contest (allowing 0 as input, handling invalid inputs, 2nd larger example).
You can use a standard approach to find m = [1, M-1] and n = [1, N], then [M, N] = n - m.
Standard approaches are easily available: Counting zeroes.

Resources