How to convert float to complex? - go

With the very simple code :
package main
import (
"fmt"
"math"
"math/cmplx"
)
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex128(x)))
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
I get the following error message :
main.go:11: cannot convert x (type float64) to type complex128
I tried different ways, but couldn't find out how to convert a float64 to complex128 (just to be able to use cmplx.Sqrt() function on a negative number).
Which is the correct way to handle this ?

You don't really want to convert a float64 to complex128 but rather you want to construct a complex128 value where you specify the real part.
For that can use the builtin complex() function:
func complex(r, i FloatType) ComplexType
Using it your sqrt() function:
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
}
return fmt.Sprint(math.Sqrt(x))
}
Try it on the Go Playground.
Note:
You can calculate the square root of a negative float number without using complex numbers: it will be a complex value whose real part is 0 and imaginary part is math.Sqrt(-x)i (so the result: (0+math.Sqrt(-x)i)):
func sqrt2(x float64) string {
if x < 0 {
return fmt.Sprintf("(0+%.15fi)", math.Sqrt(-x))
}
return fmt.Sprint(math.Sqrt(x))
}

Related

golang return function and assigned value

I am going to learn 'golang return function' but I'm seriously confused.
why this code return "7" ?
how the value is assigned to "y" ?
package main
import "fmt"
func maked(x float64) func(float64) float64 {
fn := func(y float64) float64 {
return x - y
}
return fn
}
func main() {
test := maked(12)
fmt.Println(test(5))
// printed 7
}
test := maked(12) returns a function like below.
fn := func(y float64) float64 {
return 12 - y
}
and now test have that function. So test(5) runs above function with y = 5.
so 12 - 5 = 7

golang operator % not defined on float64

There's a leetcode test 326. Power of Three with a Mathematics method with java:
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
}
}
When I intend to convert this solution to Golang Like
import "math"
func isPowerOfThree(n int) bool {
return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0
}
then here comes the compile error like
Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)
I check the math package but there's no supported function like % operator, Is there any valid operator like % in Golang? thanks a lot :)
TLDR: _, frac := math.Modf(f)
You could use func Mod(x, y float64) float64 in math package.
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0
}
You could also use func Modf(f float64) (int float64, frac float64).
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0
}
We can not use just below function, as there can be more than one digit after decimal in frac
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0
So to resolve this, use below logic
func isPowerOfThree(n int) bool {
quo,_ := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return n == int(math.Pow(3, quo))
}

How to get two length below the decimal point with golang?

From the source below, I want to get float type result 33.33.
If use fmt.Sprintf("%.2f", v) can work well. But want to get the result in the floatTest function. How to do?
func main() {
v := floatTest(30, 90)
fmt.Println(v)
// 33.33333333333333
vv := fmt.Sprintf("%.2f", v)
fmt.Println(vv)
// 33.33
}
func floatTest(count float64, total float64) float64 {
return (count / total * 100)
}
Multiply by 100; truncate via int conversion; convert back to float32 and divide by 100:
func precision2(f float64) float64 {
return float64(int(f*100)) / 100
}
https://play.golang.org/p/jbsdeQKgJji
This link has examples using the math package - but I generally try to avoid including packages for trivial operations.

Can anyone explain the compute(fn func()) code in the Go Tour website?

package main
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow))
}
Is the fn func() a function inside a function?? Can someone help with what is exactly the func compute doing here?. And I'm quite new to GO programming.
A closure is a function value that references variables from outside
its body. The function may access and assign to the referenced
variables; in this sense the function is "bound" to the variables.
In your case, compute contains a closure function. Function is passed to the compute function as an argument whose returned value is float64 which is then called in the compute function.
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4) // calling the function.
}
Since there are two functions created with same number of arguments, one of which is hypot.
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
which takes two float64 values as an argument and then returns a float64 value, while another function is in package math of golang which is math.pow
func Pow(x, y float64) float64 // Pow returns x**y, the base-x exponential of y.
whose definition is similar, which let us two pass any type of function as an argument to the compute function.
Take for an example on Go Playground

How to test whether a float is a whole number in Go?

I originally tried this, however the % operator isn't defined for float64.
func main(){
var a float64
a = 1.23
if a%1 == 0{
fmt.Println("yay")
}else{
fmt.Println("you fail")
}
}
Assuming that your numbers will fit into an int64, you can compare the float value with a converted integer value to see if they're the same:
if a == float64(int64(a)) { ... }
Alternatively, if you need the entire float64 domain, you can use the math.Trunc function, with something like:
if a == math.Trunc(a) { ... }
For example, the following code correctly outputs yay, on testing over at the Go playground:
package main
import (
"fmt"
"math"
)
func main() {
var a float64 = 2.00
if a == math.Trunc(a) {
fmt.Println("yay")
} else {
fmt.Println("you fail")
}
}
You can use the math.Modf function:
const epsilon = 1e-9 // Margin of error
if _, frac := math.Modf(math.Abs(a)); frac < epsilon || frac > 1.0 - epsilon {
// ...
}
epsilon is necessary here since floating point math is not precise (e.g. float64(.3)+float64(.6)+float64(.1) != 1)
From the godoc:
func Modf(f float64) (int float64, frac float64)
Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.
How about math.Trunc? It truncates a float64 to its whole-number component.
For example, something like:
if a.Trunc() == a {
// ...
}
Beware of the usual considerations about floating-point representation limitations. You might wish to check whether a.Trunc() is within some small range of a, to account for values like 1.00000000000000002.
I solved it like so:
isWhole := int(value * 100) == int(value) * 100
Adjust the number of digits in the factor, e.g. multiply by 10000 to check 4 digits.
I think the following code might be useful,
func main(){
var (
a float64
b float64
c float64
)
a = 1.23
b = float64(int64(a))
c = a - b
if c > 0 {
fmt.Println("Not a Whole Number")
} else {
fmt.Println("Whole Number")
}
}

Resources