How to pattern match 0.0 in SML? [duplicate] - functional-programming

This question already has an answer here:
Why can't I compare reals in Standard ML?
(1 answer)
Closed 4 years ago.
I have the following code:
datatype complex = RealImg of real * real | Infinity;
fun divisionComplex(RealImg(a, b), RealImg(0.0, 0.0)) = Infinity
fun divisionComplex(RealImg(a, b), RealImg(c, d)) =
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))
However it fails with this:
Error: syntax error: inserting EQUALOP
I am very confused. Why does this happen? I know that I can't compare two reals in SML, but how am I supposed to do pattern matching with 0?

As you said SML doesn't allow to pattern match real numbers, but recommends to use Real.== instead or compare the difference between these number against some delta.
What about just using a mere if statement for this? (also some Infinity cases added just to make the match against function params exhaustive, but feel free to change it, because it doesn't pretend to be correct)
datatype complex = RealImg of real * real | Infinity;
fun divisionComplex(Infinity, _) = Infinity
| divisionComplex(_, Infinity) = Infinity
| divisionComplex(RealImg(a, b), RealImg(c, d)) =
if Real.== (c, 0.0) andalso Real.== (d, 0.0)
then Infinity
else
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))

Related

Find equivalent value on different ranges

So...
I've been banging my head on the wall over this problem for a few days now, but still couldn't find a solution.
I have two ranges of numbers
A -> B
C -> D
A given number (x) is on the A -> B range.
I need to find it's equivalent in the C -> D range.
eg:
A -> B = (2 -> 4)
C -> D = (-148 -> -50)
x = 2.3
What is the equivalent value on the (-148 -> -50) range?
Your requirements are a bit loose, but I would be tempted to believe you want to find an affine transformation from the interval [2;4] to [-148;-50].
Calling f(x) = a.x + b this transformation, you have:
f(2) = 2.a + b = -148
f(4) = 4.a + b = -50
=> 2.f(2) = 4.a + 2.b = -296
=> 2.f(2) - f(4) = b = -246
=> a = (-148 - b)/2 = 49
=> f(x) = 49.x - 246
So the point you are looking for would be f(2.3) = -133.3
You can use ((X - A) * (D - C) / (B - A)) + C.
Size of first range is: B - A
Size of second range is: D - C
Ratio between (X - A) and (Y - C) should be proportional to that of (B - A) and (D - C).

O notation: 2^log(O(n^2)) = 2^O(log(n^2))?

I tried to solve this with logarithm rules:
O(n^2) = 2^O(log(n^2))
c*n^2 = 2^log(n^2c)
Im not sure that is true?
No, no, no. You can't just take logarithms.
2^log (O (n^2)) = 2 ^ log (c * n^2)) = c * n^2
2^ O (log n^2) = 2^ (c * log n^2) = (2 ^ (log n^2)) ^ c = (n^2) ^ c.
The first is just O (n^2). The second one is n raised to sum unknown but limited power.
I think this depends on what the equals sign means here. If the equals sign means
"Any function that is of 2log O(n2) is also 2O(log n2)"
Then the claim is true. Let f(n) be some function that's O(n2). This means that there's a c and n0 such that for any n ≥ n0, we know that f(n) ≤ cn2. Therefore, for any n ≥ n0, we know that
2log f(n) ≤ 2log (cn2) = 2(log c + log n2)
The function log c + log n2 is itself O(log n2), so we see that
2log f(n) ≤ 2(log c + log n2) = 2O(log n2)
On the other hand, if the equals sign means
"The class of functions that is 2log O(n2) is the same class of functions that is 2O(log n2)"
then the claim is false. For example, the function n4 is in the second class because it can be written as 22 log n2, but it's not in the first class.
Hope this helps!

Can an expression with multiple modulo operators (a % b % c) be reduced to something else?

Note: I'm assuming all operators below are left-associative.
a - b - c is equal to a - (b + c).
a / b / c is equal to a / (b * c).
Are there any similar equivalences for the modulo operator?
I've figured that a % b % c is equal to a % b if b <= c and a % c if b > c && b % c == 0. However, I can't figure out what a % b % c equals when b > c && b % c != 0. Is there a more general or elegant way to think about chained modulo operators? Additionally, can you think of any algorithms or usages of chained modulo operators of the last type?
Let's take b = q0*c + r0
You decompose
a = q1 * b + r1
r1 = q2 * c + r2
a = q1 * (q0 * c + r0) + q2 * c + r2
a = (q1 * q0 + q2) * c + q1 * r0 + r2
So you can say that
r2 = (a - q1 * r0) % c
Or in other words
(a%b%c) = (a - (a/b)*(b%c)) % c
This also works when b<c, because (a - (a/b)*b) is just a%b
But I doubt that this is very usefull
Chained modulo operators have no particular meaning in general, and the result may actually be ill-defined.
If you think of modulo p as a projection from integral numbers to some set {k, ... k + p - 1} then chaining two projections may not be clearly defined mathematically since the chaining depends on the choice of k (more precisely, chaining % p and % q depends on k % q).
To take this to the programming world, note that the C standard mandates that the sign of a % b is implementation defined when a is not positive.
As an example: -1 % 3 may be -1 or 2 depending on the implementation. Then, (-1 % 3) % 2 may be 0, 1, or -1 one depending on the implementation...

Drawing a triangle in a coordinate plane given its three sides

The length of three sides of the triangle, a, b and c will be given, and I need to find the coordinates of the vertices. The center (probably the circumcenter) can either be the origin or (x,y).
Can anyone point me in the right direction?
I've read brainjam's answer and checked whether his answer is true and he is right.
Calculation:
O(0;0), A(a;0) and B(x;y) are the three points of the triangle. C1 is the circle around A and r1 = c; C2 is the circle around O and r2 = b. B(X;Y) is the intersection of C1 and C2, which means that the point is on both of the circles.
C1: (x - a) * (x - a) + y * y = c * c
C2: x * x + y * y = b * b
y * y = b * b - x * x
(x - a) * (x - a) + b * b - x * x = c * c
x * x - 2 * a * x + a * a + b * b - x * x - c * c = 0
2 * a * x = (a * a + b * b - c * c)
x = (a * a + b * b - c * c) / (2 * a)
y * y = b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a))
y = +- sqrt(b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a)))
Place the first vertex at the origin (0,0). Place the second vertex at (a,0). To compute the third vertex, find the intersection of the two circles with centers (0,0) and (a,0) and radii b and c.
Update: Lajos Arpad has given the details of computing the location of the third point in this answer. It boils down to (x,y) where x = (b2+a2-c2)/2a and y=±sqrt(b2-x2)
This question and the answers helped me out today in implementing this. It will calculate the unknown vertices, "c" of circle intersections given 2 known points (a, b) and the distances (ac_length, bc_length) to the 3rd unknown vertex, "c".
Here is my resulting python implementation for anyone interested.
I also referenced the following:
http://mathworld.wolfram.com/RadicalLine.html
http://mathworld.wolfram.com/Circle-CircleIntersection.html
Using django's geos module for the Point() object, which could be replaced with shapely, or point objects removed altogether really.
from math import sqrt
from django.contrib.gis.geos import Point
class CirclesSeparate(BaseException):
pass
class CircleContained(BaseException):
pass
def discover_location(point_a, point_b, ac_length, bc_length):
"""
Find point_c given:
point_a
point_b
ac_length
bc_length
point_d == point at which the right-angle to c is formed.
"""
ab_length = point_a.distance(point_b)
if ab_length > (ac_length + bc_length):
raise CirclesSeparate("Given points do not intersect!")
elif ab_length < abs(ac_length - bc_length):
raise CircleContained("The circle of the points do not intersect")
# get the length to the vertex of the right triangle formed,
# by the intersection formed by circles a and b
ad_length = (ab_length**2 + ac_length**2 - bc_length**2)/(2.0 * ab_length)
# get the height of the line at a right angle from a_length
h = sqrt(abs(ac_length**2 - ad_length**2))
# Calculate the mid point (point_d), needed to calculate point_c(1|2)
d_x = point_a.x + ad_length * (point_b.x - point_a.x)/ab_length
d_y = point_a.y + ad_length * (point_b.y - point_a.y)/ab_length
point_d = Point(d_x, d_y)
# get point_c location
# --> get x
c_x1 = point_d.x + h * (point_b.y - point_a.y)/ab_length
c_x2 = point_d.x - h * (point_b.y - point_a.y)/ab_length
# --> get y
c_y1 = point_d.y - h * (point_b.x - point_a.x)/ab_length
c_y2 = point_d.y + h * (point_b.x - point_a.x)/ab_length
point_c1 = Point(c_x1, c_y1)
point_c2 = Point(c_x2, c_y2)
return point_c1, point_c2
When drawing an unknown triangle, it's usually easiest to pick one side (say, the longest) and place it horizontally or vertically. The endpoints of that side make up two of the triangle's vertices, and you can calculate the third by subdividing the triangle into two right triangles (the other two sides are the hypotenuses) and using the inverse sine/cosine functions to figure out the missing angles. By subdividing into right triangles, I mean something that looks like the image here: http://en.wikipedia.org/wiki/File:Triangle.TrigArea.svg Your first side would be AC in that drawing.
Once you have the triangle figured out, it should be easy to calculate it's center and translate it so that it is centered on whatever arbitrary center point you like.
First check the that the triangle is possible:
a+b >= c
b+c >= a
c+a >= b
Then, if it is, solve for the intersection of the two circles. The basic vertices are
{0,0}, {a,0}, {x,y}
where
x = (a^2-b^2+c^2)/(2a)
y = sqrt(c^2-x^2)
Finding the circumcenter is pretty easy from this point.

No idea how to solve SICP exercise 1.11

Exercise 1.11:
A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n > 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.
Implementing it recursively is simple enough. But I couldn't figure out how to do it iteratively. I tried comparing with the Fibonacci example given, but I didn't know how to use it as an analogy. So I gave up (shame on me) and Googled for an explanation, and I found this:
(define (f n)
(if (< n 3)
n
(f-iter 2 1 0 n)))
(define (f-iter a b c count)
(if (< count 3)
a
(f-iter (+ a (* 2 b) (* 3 c))
a
b
(- count 1))))
After reading it, I understand the code and how it works. But what I don't understand is the process needed to get from the recursive definition of the function to this. I don't get how the code could have formed in someone's head.
Could you explain the thought process needed to arrive at the solution?
You need to capture the state in some accumulators and update the state at each iteration.
If you have experience in an imperative language, imagine writing a while loop and tracking information in variables during each iteration of the loop. What variables would you need? How would you update them? That's exactly what you have to do to make an iterative (tail-recursive) set of calls in Scheme.
In other words, it might help to start thinking of this as a while loop instead of a recursive definition. Eventually you'll be fluent enough with recursive -> iterative transformations that you won't need to extra help to get started.
For this particular example, you have to look closely at the three function calls, because it's not immediately clear how to represent them. However, here's the likely thought process: (in Python pseudo-code to emphasise the imperativeness)
Each recursive step keeps track of three things:
f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3)
So I need three pieces of state to track the current, the last and the penultimate values of f. (that is, f(n-1), f(n-2) and f(n-3).) Call them a, b, c. I have to update these pieces inside each loop:
for _ in 2..n:
a = NEWVALUE
b = a
c = b
return a
So what's NEWVALUE? Well, now that we have representations of f(n-1), f(n-2) and f(n-3), it's just the recursive equation:
for _ in 2..n:
a = a + 2 * b + 3 * c
b = a
c = b
return a
Now all that's left is to figure out the initial values of a, b and c. But that's easy, since we know that f(n) = n if n < 3.
if n < 3: return n
a = 2 # f(n-1) where n = 3
b = 1 # f(n-2)
c = 0 # f(n-3)
# now start off counting at 3
for _ in 3..n:
a = a + 2 * b + 3 * c
b = a
c = b
return a
That's still a little different from the Scheme iterative version, but I hope you can see the thought process now.
I think you are asking how one might discover the algorithm naturally, outside of a 'design pattern'.
It was helpful for me to look at the expansion of the f(n) at each n value:
f(0) = 0 |
f(1) = 1 | all known values
f(2) = 2 |
f(3) = f(2) + 2f(1) + 3f(0)
f(4) = f(3) + 2f(2) + 3f(1)
f(5) = f(4) + 2f(3) + 3f(2)
f(6) = f(5) + 2f(4) + 3f(3)
Looking closer at f(3), we see that we can calculate it immediately from the known values.
What do we need to calculate f(4)?
We need to at least calculate f(3) + [the rest]. But as we calculate f(3), we calculate f(2) and f(1) as well, which we happen to need for calculating [the rest] of f(4).
f(3) = f(2) + 2f(1) + 3f(0)
↘ ↘
f(4) = f(3) + 2f(2) + 3f(1)
So, for any number n, I can start by calculating f(3), and reuse the values I use to calculate f(3) to calculate f(4)...and the pattern continues...
f(3) = f(2) + 2f(1) + 3f(0)
↘ ↘
f(4) = f(3) + 2f(2) + 3f(1)
↘ ↘
f(5) = f(4) + 2f(3) + 3f(2)
Since we will reuse them, lets give them a name a, b, c. subscripted with the step we are on, and walk through a calculation of f(5):
Step 1: f(3) = f(2) + 2f(1) + 3f(0) or f(3) = a1 + 2b1 +3c1
where
a1 = f(2) = 2,
b1 = f(1) = 1,
c1 = 0
since f(n) = n for n < 3.
Thus:
f(3) = a1 + 2b1 + 3c1 = 4
Step 2: f(4) = f(3) + 2a1 + 3b1
So:
a2 = f(3) = 4 (calculated above in step 1),
b2 = a1 = f(2) = 2,
c2 = b1 = f(1) = 1
Thus:
f(4) = 4 + 2*2 + 3*1 = 11
Step 3: f(5) = f(4) + 2a2 + 3b2
So:
a3 = f(4) = 11 (calculated above in step 2),
b3 = a2 = f(3) = 4,
c3 = b2 = f(2) = 2
Thus:
f(5) = 11 + 2*4 + 3*2 = 25
Throughout the above calculation we capture state in the previous calculation and pass it to the next step,
particularily:
astep = result of step - 1
bstep = astep - 1
cstep = bstep -1
Once I saw this, then coming up with the iterative version was straightforward.
Since the post you linked to describes a lot about the solution, I'll try to only give complementary information.
You're trying to define a tail-recursive function in Scheme here, given a (non-tail) recursive definition.
The base case of the recursion (f(n) = n if n < 3) is handled by both functions. I'm not really sure why the author does this; the first function could simply be:
(define (f n)
(f-iter 2 1 0 n))
The general form would be:
(define (f-iter ... n)
(if (base-case? n)
base-result
(f-iter ...)))
Note I didn't fill in parameters for f-iter yet, because you first need to understand what state needs to be passed from one iteration to another.
Now, let's look at the dependencies of the recursive form of f(n). It references f(n - 1), f(n - 2), and f(n - 3), so we need to keep around these values. And of course we need the value of n itself, so we can stop iterating over it.
So that's how you come up with the tail-recursive call: we compute f(n) to use as f(n - 1), rotate f(n - 1) to f(n - 2) and f(n - 2) to f(n - 3), and decrement count.
If this still doesn't help, please try to ask a more specific question — it's really hard to answer when you write "I don't understand" given a relatively thorough explanation already.
I'm going to come at this in a slightly different approach to the other answers here, focused on how coding style can make the thought process behind an algorithm like this easier to comprehend.
The trouble with Bill's approach, quoted in your question, is that it's not immediately clear what meaning is conveyed by the state variables, a, b, and c. Their names convey no information, and Bill's post does not describe any invariant or other rule that they obey. I find it easier both to formulate and to understand iterative algorithms if the state variables obey some documented rules describing their relationships to each other.
With this in mind, consider this alternative formulation of the exact same algorithm, which differs from Bill's only in having more meaningful variable names for a, b and c and an incrementing counter variable instead of a decrementing one:
(define (f n)
(if (< n 3)
n
(f-iter n 2 0 1 2)))
(define (f-iter n
i
f-of-i-minus-2
f-of-i-minus-1
f-of-i)
(if (= i n)
f-of-i
(f-iter n
(+ i 1)
f-of-i-minus-1
f-of-i
(+ f-of-i
(* 2 f-of-i-minus-1)
(* 3 f-of-i-minus-2)))))
Suddenly the correctness of the algorithm - and the thought process behind its creation - is simple to see and describe. To calculate f(n):
We have a counter variable i that starts at 2 and climbs to n, incrementing by 1 on each call to f-iter.
At each step along the way, we keep track of f(i), f(i-1) and f(i-2), which is sufficient to allow us to calculate f(i+1).
Once i=n, we are done.
What did help me was running the process manually using a pencil and using hint author gave for the fibonacci example
a <- a + b
b <- a
Translating this to new problem is how you push state forward in the process
a <- a + (b * 2) + (c * 3)
b <- a
c <- b
So you need a function with an interface to accept 3 variables: a, b, c. And it needs to call itself using process above.
(define (f-iter a b c)
(f-iter (+ a (* b 2) (* c 3)) a b))
If you run and print each variable for each iteration starting with (f-iter 1 0 0), you'll get something like this (it will run forever of course):
a b c
=========
1 0 0
1 1 0
3 1 1
8 3 1
17 8 3
42 17 8
100 42 17
235 100 42
...
Can you see the answer? You get it by summing columns b and c for each iteration. I must admit I found it by doing some trail and error. Only thing left is having a counter to know when to stop, here is the whole thing:
(define (f n)
(f-iter 1 0 0 n))
(define (f-iter a b c count)
(if (= count 0)
(+ b c)
(f-iter (+ a (* b 2) (* c 3)) a b (- count 1))))
A function f is defined by the rule that f(n) = n, if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3), if n > 3. Write a procedure that computes f by means of a recursive process.
It is already written:
f(n) = n, (* if *) n < 3
= f(n - 1) + 2f(n - 2) + 3f(n - 3), (* if *) n > 3
Believe it or not, there was once such a language. To write this down in another language is just a matter of syntax. And by the way, the definition as you (mis)quote it has a bug, which is now very apparent and clear.
Write a procedure that computes f by means of an iterative process.
Iteration means going forward (there's your explanation!) as opposed to the recursion's going backwards at first, to the very lowest level, and then going forward calculating the result on the way back up:
f(0) = 0
f(1) = 1
f(2) = 2
f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3)
= a + 2b + 3c
f(n+1) = f(n ) + 2f(n - 1) + 3f(n - 2)
= a' + 2b' + 3c' where
a' = f(n) = a+2b+3c,
b' = f(n-1) = a,
c' = f(n-2) = b
......
This thus describes the problem's state transitions as
(n, a, b, c) -> (n+1, a+2*b+3*c, a, b)
We could code it as
g (n, a, b, c) = g (n+1, a+2*b+3*c, a, b)
but of course it wouldn't ever stop. So we must instead have
f n = g (2, 2, 1, 0)
where
g (k, a, b, c) = g (k+1, a+2*b+3*c, a, b), (* if *) k < n
g (k, a, b, c) = a, otherwise
and this is already exactly like the code you asked about, up to syntax.
Counting up to n is more natural here, following our paradigm of "going forward", but counting down to 0 as the code you quote does is of course entirely equivalent.
The corner cases and possible off-by-one errors are left out as exercise non-interesting technicalities.

Resources