I am trying to get a mathmetical equation to recognise a + /- sign of an integer (either -1 or +1) entered in a UItextfield (s1, s2). So if the user enters different signs the equations will be subtracted from each other.
It seems that the sign is not being recognised for some reason and the program just adds d1 and d2.
-(IBAction)calculateD:(id)sender{
float n1, r1, n2, r1, d, d1, d2;
int s1, s2;
s1= [textfieldS1.text intvalue]; //etc for all variables
d1 = s1 * ((n1-1)/r1);
d2 = s2 * ((n2-1)/r2);
if (s1 != s2) { d = d1 - d2;}
else { d = d1 + d2;
}}
Any problems apparent in this code please?
I have no idea what you are trying to do here. Variables are not initialized and there is no specific reference to actual UITextField inside of the -calculateD: method. With this said, here are some hints, hope it will come in hand.
The signs s1, s2 are actually taken twice into a consideration. Once to produce d1, d2, and later to decide the (s1 != s2). Because of this, the latter will make sure you add two numbers of the same sign, possibly negating what you really want to obtain here. Example:
say that s1=+1, s1=+1, then you got d = ((n1-1)/r1) + ((n2-1)/r2);
say that s1=+1, s1=-1, then you got d = ((n1-1)/r1) + ((n2-1)/r2); the same as before;
Just drop the if, and leave a single: d = d1 + d2.
Related
I have a quick question with respect to the doParallel package in R. I have an optimize.R file where it contains roughly 18 functions A1, A2, A3, A4, ..., A18 within it, and A18 would basically contain all the functions A1, A2, A3,..., A17. I have another result.R file, where I used import every functions within optimize.R into the Global Environment of RStudio (located on the upper-right corner of RStudio). In addition, within result.R file, I have a function F that calls function E under the loop foreach(..., .export = c(".GlobalEnv")) %dopar% {do something}.
Now, in the final.R file (which is the main file), I use source(/C:/Users/[Name]/Desktop/result.R, echo = F). Within final.R, I have a function res that calls function F.
However, when I execute this final.R file, I got the error message: task 1: cannot find variable C , which is weird because C is a function, not a variable. Also, it seems to me the .export = c(".GlobalEnv") fails to work, as function C is already in the Global Environment. Can anyone suggest some ways to overcome this kind of issue? I tried to export
Flow of the 3 files.
final.R file
source(/C:/Users/[Name]/Desktop/result.R, echo = F)
library(doParallel)
registerDoParallel(4)
res <- function(var_x, var_y) {
best.rev <- foreach(i=1:5, .export = c(".GlobalEnv")) %dopar% {
F(var_x, var_y)
do something else
}
output <- best.rev
}
result.R file
source(/C:/Users/[Name]/Desktop/optimize.R, echo = F)
F <- function(var1, var2) {
E(var1, var2)
do something else
}
optimize.R file
A1 <- function(x1, x2) {....}
A2 <- function(x1, x3, x4) {...}
A3 <- function(x1, x2, x3) {...}
....
A18 <- function(x1,x2,x3,x4,...,x8) {
a1 <- A1(x1, x2)
a2 <- A2(a1, x3, x4)
a3 <- A3(a1, a2, x3)
return(list(a1, a2, a3))
}
Consider this function:
double calculate_geoHeading(double [] x, double [] y) {
/+ +++++++++
++ This function will return the heading of the best fit line
++
+/
double r;
real xMean = mean(x);
real yMean = mean(y);
real denom = 0;
real numer = 0;
//double cookDistance NOIMPL
for( int i = 0; i < x.length; i++) {
numer += (x[i] - xMean) * (y[i] - yMean);
denom += (x[i] - xMean) * (x[i] - xMean);
}
real b1 = numer / denom ;
real b0 = yMean - (b1 *xMean);
real y0 = b0 + b1 * x[0];
real x0 = x[0];
real yn = b0 + b1 * x[$-1];
real xn = x[$-1];
r = atan2((yn-y0), (xn-x0));
foreach(XX; x) {
auto YY = b0 + b1 * XX;
print_highPrecision_geoArray([YY, XX]);
}
return r;
}
It is written in D. Th array x is a double array of Longitudes, and y is for Latitude. I compute the linear regression through these points, and then compute the slope of this line. This slope is the heading of the path described by these points.
This normally Works,
For this input :
x = [9.87837003485911,9.87836998511341,9.87836993536771,9.878369885622,9.87836966666667,9.87836975210867,9.87836983755067,9.87836992299267,9.87837000843468,9.87837009387668]
y =
[49.0199479977727,49.0199513307348,49.0199546636969,49.0199579966591,49.0199726666667,49.0199759989048,49.0199793311429,49.019982663381,49.0199859956191,49.0199893278572]
I am having this output :
The Red markers show you the first half of the input array, and the second half of the input array is given by the pink ones.
Then, I also have the output of the interpolated y or Latitude values. These values are held in function by the variable YY. The corresponding x or Longitude values are also present.
These interpolated points are also plotted . Half of them are in green - which has the same x values red part of the input. The rest are cyan, which corresponds to the pink part.
The input is a monotonically increasing function, whereas the interpolated output is monotonically decreasing.
Question : What is my error?
My attempt at solution : I have tried with 80 000 other randomly generated Lat / Lon pairs : it works everywhere in those pairs.
So, I am stuck.
The print_highPrecision_geoArray is properly defined, so is the mean function.
I do not want to blame this on a floating point error.
I need an algorithm, that applies the linear regression properly.
Please help.
So, I am creating a mathematical program, it has a couple of functions, one of the function is a decimal place holder, what this is:
the user is asked how many decimal places between 1 and 5. he would like his answers to be shown for the different mathematical function.
Let’s say the user chooses the answer to be to 4 decimal places, he then sets this up and he chooses the quadratic equation solver, he is asked for A,B,C values, once it is calculated the, let say he gives inputs of 1, -8 and 15, the answer is -3 and 5. However as he had chosen his answer to be to 4 decimal places the answer should be produced as -3.0000 and 5.0000
I can not get this to work, here is my code below, can someone help me solve this, been stuck on it for a couple of days now
I have tried to round the number by the Decimal place input from the user: not working
'Decimal place rule
Sub Accuracy()
Line1:
Dim DP
Console.WriteLine("Please Enter the Decimial Limit between 1-5: ")
DP = Double.Parse(Console.ReadLine())
If (DP > 5) Then
Console.WriteLine("Error, Decimial Limit is between 1 and 5, Please Try Again!")
GoTo Line1
Else
DP = DP
Console.Write("Decimial Limit has been Set Succuesfully to " & DP & " Decimal Places")
End If
End Sub
'Quadratic Equation function
Sub QuadraticFunction()
Dim a, b, c As Integer
Dim d, x1, x2 As Double
line1:
Console.WriteLine("Please Input a Non-Zero Number, A: ")
a = Console.ReadLine()
If (a = 0) Then
Console.WriteLine("Error, Number must not be 0, Try Again!")
GoTo line1
End If
Console.WriteLine("Please Input The Value of, B: ")
b = Console.ReadLine()
Console.Write("Please Input the Value of, C: ")
c = Console.ReadLine()
d = b * b - (4 * a * c)
If (d = 0) Then
Console.WriteLine("Both Roots Are Equal.")
x1 = -b / (2.0 * a)
x2 = x1
x1 = Math.Round(x1, DP)
x2 = Math.Round(x1, DP)
Console.WriteLine("First Root, (Root1) = {0}", x1)
Console.WriteLine("Second Root, (Root2) = {0}", x2)
ElseIf (d > 0) Then
Console.WriteLine("Both Roots are Real and Different")
x1 = (-b + Math.Sqrt(d)) / (2 * a)
x2 = (-b - Math.Sqrt(d)) / (2 * a)
x1 = (Math.Round(x1, DP))
x2 = (Math.Round(x2, DP))
Console.WriteLine("First Root, (Root1) = {0}", x1)
Console.WriteLine("Second Root, (Root2) = {0}", x2)
Else
Console.Write("Root are Imaginary " & "No Solution")
End If
End Sub
I try to do image registration on two grayscale images where the images were taken twice with different views. The images were taking by myself using a Lifecam camera.
To register these images, I used template matching method and normalized cross correlation as similarity measure and found the right location. But the result after combination of these two images was not good as I wish. I don't know how to fix it. Do I need to do some rotation or translation first before combine it? If so, I have no idea how to get the real angle for rotation. Or do you have any idea how to fix the image result without applying any rotation?
Input image 1:
Input Image 2:
Result:
This my code:
A = imread('image1.jpg');
B = imread('image2.jpg');
[M1, N1] = size(A); % size imej A n B
[M2, N2] = size(B);
%% finding coordinated of (r2,c2)
r1 = size(A,1)/2; % midpoint of image A as coordinate
c1 = size(A,2
template = imcrop(A,[(c1-20) (r1-20) 40 40]);
[r2, c2] = normcorr(temp,B); % Normalized cross correlation
%% count distance of coordinate (r1,c1) in image A and (r2,c2)in image B
UA = r1; % distance of coordinate (r1,c1) from top in image A
BA = M1 - r1; % distance of coordinate (r1,c1) from bottom
LA = c1; % left distance from (r1,c1)
RA = N1 - c1; % right distance from (r1,c1)
UB = r2; % finding distance of coordinate (r2,c2) from top,
BB = M2 - r2; % bottom, left and right in image B
LB = c2;
RB = N2 - c2;
%% zero padding for both image
if LA > LB
L_diff = LA - LB; % value of columns need to pad with zero on left side
B = [zeros(M2,L_diff),B];
else
L_diff = LB - LA;
A = [zeros(M1,L_diff),A];
end
if RA > RB
R_diff = RA - RB; % value of columns need to pad with zero on right side
B = [B, zeros(M2,R_diff)];
else
R_diff = RB - RA;
A = [A, zeros(M1,R_diff)];
end
N1 = size(A, 2); % renew value column image A and B
N2 = size(B, 2);
if UA > UB
U_diff = UA - UB; % value of rows need to pad with zero on top
B = [zeros(U_diff,N2);B];
else
U_diff = UB - UA;
A = [zeros(U_diff,N1);A];
end
if BA > BB
B_diff = BA - BB; % value of rows need to pad with zero on bottom
B = [B; zeros(B_diff,N2)];
else
B_diff = BB - BA;
A = [A; zeros(B_diff,N1)];
end
%% find coordinate that have double value
if LA > LB
r = r1;
c = c1;
else
r = r2;
c = c2;
end
if UA >= UB
i_Start = r - UB + 1;
else
i_Start = r - UA + 1;
end
if BA >= BB
i_Stop = r + BB ;
else
i_Stop = r + BA;
end
if LA >= LB
j_Start = c - c2 + 1;
else
j_Start = c - c1 + 1;
end
if RA >= RB
j_Stop = c + RB;
else
j_Stop = c + RA;
end
%% add image A and B
A = im2double(A);
B = im2double(B);
final_im = A + B;
for i = i_Start:i_Stop
for j = j_Start:j_Stop
final_im(i,j) = final_im(i,j)/2;
end
end
final_im = im2uint8(final_im);
The answer from rayryeng in Ryan L's first link is quite applicable here. Cross-correlation likely won't provide a close enough match between the two images since the transformation between the two images is more accurately described as a homography than a 2D rigid transform.
Accurate image registration requires that you find this projective transformation. To do so you can find a set of corresponding points in the two images (using SURF, as mentioned above, usually works well) and then use RANSAC to obtain the homography's parameters from the corresponding points. RANSAC does a nice job even when some of the "corresponding" features in your two images are actually not correct matches. Once found, you can use the transformation to move one of your images to the other's point of view and fuse.
Here's a nice explanation of feature matching, RANSAC, and fusing two images with some Matlab code samples. The lecture uses SIFT features, but the idea still works for SURF.
Best published way to perform such a registration is based on fiducial points. You can choose the most clear edges or crossing points as a fiducial and then adjust the smoothness and regularization parameter to register them together.
look at the SlicerRT package. and let me know if you face any problem.
There are two random functions f1(),f2().
f1() returns 1 with probability p1, and 0 with probability 1-p1.
f2() returns 1 with probability p2, and 0 with probability 1-p2.
I want to implement a new function f3() which returns 1 with probability p3(a given probability), and returns 0 with probability 1-p3. In the implemetion of function f3(), we can use function f1() and f2(), but you can't use any other random function.
If p3=0.5, an example of implemention:
int f3()
{
do
{
int a = f1();
int b = f1();
if (a==b) continue;
// when reachs here
// a==1 with probability p1(1-p1)
// b==1 with probability (1-p1)p1
if (a==1) return 1;//now returns 1 with probability 0.5
if (b==1) return 0;
}while(1)
}
This implemention of f3() will give a random function returns 1 with probability 0.5, and 0 with probability 0.5. But how to implement the f3() with p3=0.4? I have no idea.
I wonder, is that task possible? And how to implement f3()?
Thanks in advance.
p1 = 0.77 -- arbitrary value between 0 and 1
function f1()
if math.random() < p1 then
return 1
else
return 0
end
end
-- f1() is enough. We don't need f2()
p3 = 0.4 -- arbitrary value between 0 and 1
--------------------------
function f3()
left = 0
rigth = 1
repeat
middle = left + (right - left) * p1
if f1() == 1 then
right = middle
else
left = middle
end
if right < p3 then -- completely below
return 1
elseif left >= p3 then -- completely above
return 0
end
until false -- loop forever
end
This can be solved if p3 is a rational number.
We should use conditional probabilities for this.
For example, if you want to make this for p3=0.4, the method is the following:
Calculate the fractional form of p3. In our case it is p3=0.4=2/5.
Now generate as many random variables from the same distribution (let's say, from f1, we won't use f2 anyway) as the denominator, call them X1, X2, X3, X4, X5.
We should regenerate all these random X variables until their sum equals the numerator in the fractional form of p3.
Once this is achieved then we just return X1 (or any other Xn, where n was chosen independently of the values of the X variables). Since there are 2 1s among the 5 X variables (because their sum equals the numerator), the probability of X1 being 1 is exactly p3.
For irrational p3, the problem cannot be solved by using only f1. I'm not sure now, but I think, it can be solved for p3 of the form p1*q+p2*(1-q), where q is rational with a similar method, generating the appropriate amount of Xs with distribution f1 and Ys with distribution f2, until they have a specific predefined sum, and returning one of them. This still needs to be detailed.
First to say, that's a nice problem to tweak one's brain. I managed to solve the problem for p3 = 0.4, for what you just asked for! And I think, generalisation of such problem, is not so trivial. :D
Here is how, you can solve it for p3 = 0.4:
The intuition comes from your example. If we generate a number from f1() five times in an iteration, (see the code bellow), we can have 32 types of results like bellow:
1: 00000
2: 00001
3: 00010
4: 00011
.....
.....
32: 11111
Among these, there are 10 such results with exactly two 1's in it! After identifying this, the problem becomes simple. Just return 1 for any of the 4 combinations and return 0 for 6 others! (as probability 0.4 means getting 1, 4 times out of 10). You can do that like bellow:
int f3()
{
do{
int a[5];
int numberOfOneInA = 0;
for(int i = 0; i < 5; i++){
a[i] = f1();
if(a[i] == 1){
numberOfOneInA++;
}
}
if (numberOfOneInA != 2) continue;
else return a[0]; //out of 10 times, 4 times a[0] is 1!
}while(1)
}
Waiting to see a generalised solution.
Cheers!
Here is an idea that will work when p3 is of a form a/2^n (a rational number with a denominator that is a power of 2).
Generate n random numbers with probability distribution of 0.5:
x1, x2, ..., xn
Interpret this as a binary number in the range 0...2^n-1; each number in this range has equal probability. If this number is less than a, return 1, else return 0.
Now, since this question is in a context of computer science, it seems reasonable to assume that p3 is in a form of a/2^n (this a common representation of numbers in computers).
I implement the idea of anatolyg and Egor:
inline double random(void)
{
return static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
}
const double p1 = 0.8;
int rand_P1(void)
{
return random() < p1;
}
int rand_P2(void)//return 0 with 0.5
{
int x, y; while (1)
{
mystep++;
x = rand_P1(); y = rand_P1();
if (x ^ y) return x;
}
}
double p3 = random();
int rand_P3(void)//anatolyg's idea
{
double tp = p3; int bit, x;
while (1)
{
if (tp * 2 >= 1) {bit = 1; tp = tp * 2 - 1;}
else {bit = 0; tp = tp * 2;}
x = rand_P2();
if (bit ^ x) return bit;
}
}
int rand2_P3(void)//Egor's idea
{
double left = 0, right = 1, mid;
while (1)
{
dashenstep++;
mid = left + (right - left) * p1;
int x = rand_P1();
if (x) right = mid; else left = mid;
if (right < p3) return 1;
if (left > p3) return 0;
}
}
With massive math computings, I get, assuming P3 is uniformly distributed in [0,1), then the expectation of Egor is (1-p1^2-(1-p1)^2)^(-1). And anatolyg is 2(1-p1^2-(1-p1)^2)^(-1).
Speaking Algorithmically , Yes It is possible to do that task done .
Even Programmatically , It is possible , but a complex problem .
Lets take an example .
Let
F1(1) = .5 which means F1(0) =.5
F2(2) = .8 which means F1(0) =.2
Let Suppose You need a F3, such that F3(1)= .128
Lets try Decomposing it .
.128
= (2^7)*(10^-3) // decompose this into know values
= (8/10)*(8/10)*(2/10)
= F2(1)&F2(1)*(20/100) // as no Fi(1)==2/10
= F2(1)&F2(1)*(5/10)*(4/10)
= F2(1)&F2(1)&F1(1)*(40/100)
= F2(1)&F2(1)&F1(1)*(8/10)*(5/10)
= F2(1)&F2(1)&F1(1)&F2(1)&F1(1)
So F3(1)=.128 if we define F3()=F2()&F2()&F2()&F1()&F1()
Similarly if you want F4(1)=.9 ,
You give it as F4(0)=F1(0) | F2(0) =F1(0)F2(0)=.5.2 =.1 ,which mean F4(1)=1-0.1=0.9
Which means F4 is zero only when both are zero which happens .
So making use this ( & , | and , not(!) , xor(^) if you want ) operations with a combinational use of f1,f2 will surely give you the F3 which is made purely out of f1,f2,
Which may be NP hard problem to find the combination which gives you the exact probability.
So, Finally the answer to your question , whether it is possible or not ? is YES and this is one way of doing it, may be many hacks can be made into it this to optimize this, which gives you any optimal way .