How to calculate SquareRoot of Integer without using inbuilt function in Swift Language? I tried below code & searched but didn't get better solution - swift

Just an exercise:
func mySqrt(_ x: Int) -> Int {
if x<2 { return x }
var y = x
var z = (y + (x/y)) / 2
while Double(abs(y - z)) >= 0.00001 {
y = z
z = (y + (x/y)) / 2
}
return z
}
I went through many answers in StackOverflow but couldn't get a better solution, e.g.
Best way to calculate the square root of any number in ios , Objective C and Swift
Finding square root without using sqrt function?
Take input x = 4 or any perfect square, it works fine. Now, take something like x = 8, It Time out.
Please help me out, what I am doing wrong.

The problem is you are trying to use integers for all of the calculations.
The square root of 8 is not an integer. You need to use Double for all of your variables (except optionally leave parameter as an Int). The return value needs to be a Double if you want a meaningful answer.
Here's your code using Double where needed:
func mySqrt(_ x: Int) -> Double {
if x < 2 { return Double(x) }
var y = Double(x)
var z = (y + (Double(x)/y)) / 2
while (abs(y - z)) >= 0.00001 {
y = z
z = (y + (Double(x)/y)) / 2
}
return z
}
print(mySqrt(8))
This gives the correct result.

Related

How to find the distance between a point and a line programatically?

I found something similar that gave me the general form of a line but after writing it out I came across some limitations with horizontal/vertical lines. Source here: https://math.stackexchange.com/questions/637922/how-can-i-find-coefficients-a-b-c-given-two-points
I'm not that good with math but I assume there are restrictions of the general equation of a line formula and attempting to calculate the distance with the distance formula using general coefficients of A,B,C did not work out.
Here's my original code that got the coefficients.
func computeEquationOfALineCoefficients(point1: CGPoint, point2: CGPoint) -> [CGFloat] {
// Computes the equation of a line in the form Ax + By + C = 0 thorugh
// y - y1 = (y2 - y1)/(x2 - x1) * (x - x1) or alternatively
// (y1-y2) * x + (x2-x1) * y + (x1-x2)*y1 + (y2-y1)*x1 = 0
// where a = y1 - y2, b = x2 - x1, c = (x1-x2)*y1 + (y2-y1)*x1
let x1: CGFloat = point1.x
let x2: CGFloat = point2.x
let y1: CGFloat = point1.y
let y2: CGFloat = point2.y
let A = y1 - y2
let B = x2 - x1
let C = (x1 - x2) * y1 + (y2 - y1) * x1
return [A, B, C]
}
and then the distance formula I was using
func computeDistanceBetweenPointAndLine(point: CGPoint, A: Float, B: Float, C: Float) -> Float {
let x: Float = Float(point.x)
let y: Float = Float(point.y)
let distance = abs(A * x + B * y + C) / (pow(A, 2) + pow(B, 2)).squareRoot()
return distance
}
it works fine until I introduce a horizontal line like the coordinates 0,0 and 150,0.
So I then decided to try the route with the perpendicular intersection between a point and a line but I'm stumped at solving for x by setting two equations equal to each other. I found a resource for that here: https://sciencing.com/how-to-find-the-distance-from-a-point-to-a-line-13712219.html but I am not sure how this is supposed to be represented in code.
Any tips or resources I may have yet to find are appreciated. Thank you!

How do you swap two variables of any type without using third in swift?

I know how to swap int like below:
var x = 5
var y = 7
x = x + y
y = x - y
x = x - y
print(x)
print(y)
But how can I swap two variables of any other type without using a third variable ?
Use tuples!
var a = "a"
var b = "b"
(b, a) = (a, b)
This works for any type, or any number of variables.
Another way that is similar to your approach with Ints:
a += b
b = String(a.dropLast(b.count))
a = String(a.dropFirst(b.count))

Splitting method algorithm

(x^3 - 2x^2 - 5) is my equation.First of all I have two values like x = 2 and x = 4. My first two values must be count for equation and them results must be negative and positive each time. And second step is (2 + 4) / 2 = 3 this time x = 3 in equation. And the math operation continue with last one positive value and one negative value. I try this
var x = 2.0
var equation = pow(x, 3) - 2 * pow(x, 2) - 5
switch x {
case x : 2
equation = pow(x, 3) - 2 * pow(x, 2) - 5
case x : 4
equation = pow(x, 3) - 2 * pow(x, 2) - 5
default:
0
}
print(equation)
How can I assign first two values like 2 and 4 for one var x ?
Apparently you want to implement the bisection method to find the (real) solution (“root”) of an equation. The first step is to define that equation as a function, so that it can be evaluated at various points:
func f(_ x: Double) -> Double {
return pow(x, 3) - 2 * pow(x, 2) - 5
}
Then you need two variables for the left and right boundary of the current interval. These must be chosen such that f(x) has opposite signs at the boundaries. In your example:
var xleft = 2.0 // f(xleft) < 0
var xright = 4.0 // f(xright) > 0
Now you can start the iteration: Compute f(x) at the midpoint of the current interval, and replace xleft of xright, depending on whether f(x) is negative or positive. Continue until the approximation is good enough for your purposes:
let eps = 0.0000001 // Desired precision
let leftSign = f(xleft).sign
repeat {
let x = (xleft + xright)/2.0
let y = f(x)
if y == 0 {
xleft = x
break
} else if y.sign == leftSign {
xleft = x
} else {
xright = x
}
// print(xleft, xright)
} while xright - xleft > eps
// Print approximate solution:
print(xleft)
The next step would be to implement the bisection method itself as a function:
func bisect(_ f: ((Double) -> Double), xleft: Double, xright: Double, eps: Double = 1.0e-6) -> Double {
let yleft = f(xleft)
let yright = f(xright)
precondition(yleft * yright <= 0, "f must have opposite sign at the boundaries")
var xleft = xleft
var xright = xright
repeat {
let x = (xleft + xright)/2.0
let y = f(x)
if y == 0 {
return x
} else if y.sign == yleft.sign {
xleft = x
} else {
xright = x
}
} while xright - xleft > eps
return (xleft + xright)/2.0
}
so that it can be used with arbitrary equations:
let sol1 = bisect({ x in pow(x, 3) - 2 * pow(x, 2) - 5 }, xleft: 2.0, xright: 4.0)
print(sol1) // 2.690647602081299
let sol2 = bisect({ x in cos(x/2)}, xleft: 3.0, xright: 4.0, eps: 1.0e-15)
print(sol2) // 3.1415926535897936

Fastest Inverse Square Root on iPhone (Swift, not ObjectC)

Refer to
Fastest Inverse Square Root on iPhone
I need do a "Fastest Inverse Square Root" on iPhone iOS Swift, which is supposed to be faster than 1/sqrt(float).
How do I do it?
In embedded C programming, it is:
// Fast inverse square-root
// See: http://en.wikipedia.org/wiki/Fast_inverse_square_root
func invSqrt(x: Float) -> Float {
var halfx : Float = 0.5 * x
var y : Float = x
long i = *(long*)&y
i = 0x5f3759df - (i>>1)
y = *(float*)&i
y = y * (1.5 - (halfx * y * y))
return y
}
The only tricky part is how to do the forced conversions between floating
point numbers and integer types, and the easiest way is to use
memcpy():
// Fast inverse square-root
// See: http://en.wikipedia.org/wiki/Fast_inverse_square_root
func invSqrt(x: Float) -> Float {
let halfx = 0.5 * x
var y = x
var i : Int32 = 0
memcpy(&i, &y, 4)
i = 0x5f3759df - (i >> 1)
memcpy(&y, &i, 4)
y = y * (1.5 - (halfx * y * y))
return y
}
I made some performance tests on an iPhone 6s with 1.000.000 random
floating point numbers in the range 0 ... 1000, and it turned out
that invSqrt(x) is about 40% faster than 1.0/sqrt(x).
The maximal relative error was below 0.176%, confirming the bound in
the Wikipedia article.
I also made a test with vvrsqrtf from the
Accelerate framework, but this was actually slower than
calling 1.0/sqrt(x), at least when called with single floating
point numbers.
As of Swift 3, memcpy() can be replaced by the bitPattern:
method of Float and the corresponding constructor from UInt32:
func invSqrt(x: Float) -> Float {
let halfx = 0.5 * x
var i = x.bitPattern
i = 0x5f3759df - (i >> 1)
var y = Float(bitPattern: i)
y = y * (1.5 - (halfx * y * y))
return y
}

How can I convert C# code to MATLAB?

I have this C# code and I am trying to convert it to MATLAB code.
float randomFloat()
{
return (float)rand() / (float)RAND_MAX;
}
int calculateOutput(float weights[], float x, float y)
{
float sum = x * weights[0] + y * weights[1] + weights[2];
return (sum >= 0) ? 1 : -1;
}
I don't think we can use float and int in MATLAB. How do I change the code?
the first one is simply: rand()
the second function can be written as:
if ( [x y 1]*w(:) >=0 )
result = 1;
else
result = -1;
end
The built-in function rand() already does what you're trying to do with randomFloat().
For calculateOutput you can use something fairly similar to what you've got, but as you say you don't need to declare types:
function result = calculateOutput (weights, x, y)
s = x * weights(1) + y * weights(2) + weights(3);
if s >= 0
result = 1;
else
result = -1;
end
end
Note that matlab vectors are one-based, so you need to adjust the indexing.
If you want to generalise this to arbitrary vectors it would make sense to "vectorize" it, but for this simple case a straight translation like this should be fine.