Float64 in golang - go

I am currently doing a simple variance function with float64. However i encountered a problem when dividing the float64 with the NaN result.
In my main I have a simple loop to sum all the data minus the mean. after that i am doing the division by the length of my container. Anyone know what mistake I did?
for _, letter := range floatContainer {
variance += VarSqrt(letter, average)
}
variance /= float64(len(floatContainer) - 1) <---- Here is the problem
func VarSqrt(n, mean float64) float64 {
return math.Sqrt(n - mean)
}

to calculate variance, you should sum all the data minus the mean's square, not sqrt, and the length of array should > 1
here is the sample code
func mean(nums []float64) float64 {
var s float64 = 0
for _, x := range nums {
s += x
}
return s / float64(len(nums))
}
func variance(nums []float64) float64 {
var res float64 = 0
var m = mean(nums)
var n = len(nums)
for _, x := range nums {
res += (x - m) * (x - m)
}
return res / float64(n-1)
}

Related

Slices of crescent subsequences

I have a slice of float64 containing some values and a float value epsilon, what I would like to do is:
assuming that the slice got already sorted I want to go through the slice of float64 and check that every value of the sequence is bigger than the next one of at least value epsilon.
If it’s not bigger than the value epsilon than we will append on a slice of slices a new slice containing all the numbers read and the next numbers will be put in a new slice until the same condition happens or we finish going through the slice.
INPUT:
Epsilon : 0,001
Slice of floats64: [0,4351 0,455 0,4356 0,4359 0,4362]
DESIRED OUTPUT:
Returned slices: [ 0,4351 0,4355 ] [ 0,4356 0,4359 0,4362 ]
This is how I've tried to implement this:
for i := 0; i < len(sliceFloat); i++ {
for j := i + 1; j < len(sliceFloat); j++ {
if sliceFloat[i] - sliceFloat[j] <= epsilon {
sliceOfSlices = append(sliceOfSlices, sliceFloat[i:j])
} else {
continue
}
}
}
return sliceOfSlices
This is the output that I get:
[[0.4351] [0.4351 0.4355] [0.4351 0.4355 0.4356] [0.4351 0.4355 0.4356 0.4359] [0.4355] [0.4355 0.4356] [0.4355 0.4356 0.4359] [0.4356] [0.4356 0.4359] [0.4359]]
What am I doing wrong and how can I fix this?
The test input you posted is clearly wrong: GIGO: Garbage in, garbage out.
Epsilon : 0,001
Slice of floats64: [0,4351 0,455 0,4356 0,4359 0,4362]
Your code does not attempt to fully implement the specification.
else {
continue
}
After fixing all the bugs:
package main
import "fmt"
func crescents(s []float64, epsilon float64) [][]float64 {
var ss [][]float64
for i, f := range s {
if i == 0 || f <= s[i-1]+epsilon {
ss = append(ss, []float64(nil))
}
ss[len(ss)-1] = append(ss[len(ss)-1], f)
}
return ss
}
func main() {
s := []float64{0.4351, 0.4355, 0.4356, 0.4359, 0.4362}
epsilon := 0.0001
ss := crescents(s, epsilon)
fmt.Println(s, epsilon)
fmt.Println(ss)
}
https://go.dev/play/p/h-SxeIWPuu-
[0.4351 0.4355 0.4356 0.4359 0.4362] 0.0001
[[0.4351 0.4355] [0.4356 0.4359 0.4362]]

how to simplimize my go script because always get time out in hackerrank

I have a test interview as a Go Developer and have to do some of the tasks on hackerrank.
I've done the task, but when I submit my script it always "times out".. maybe because there are a lot of loops that I use to do this function, and the task is :
So, my solution are :
Loop from a to b with a increment.
Define the digit sum with modulus by 10, sum the result with the leftover.
Define the square sum with converting int(a) to string then use for-range to sum the values.
checking if digit sum and square sum is a prime number, if so then count++
My script is :
func main() {
fmt.Printf("Jadi ada %d bilangan prima \n", luckyNumbers(1, 20))
}
func luckyNumbers(a int64, b int64) int64 {
count := 0
for min, max := a, b; min <= max; min++ {
squareSum := digitSquare(min)
digitSum := digitSum(min)
if isPrime(digitSum) && isPrime(squareSum) {
count++
}
}
return int64(count)
}
func digitSquare(number int64) int64 {
numStr := strconv.Itoa(int(number))
var firstDigit, secondDigit int
for _, digit := range numStr {
numInt, _ := strconv.Atoi(string(digit))
pow := int(math.Pow(float64(numInt), 2))
if firstDigit == 0 {
firstDigit += pow
} else {
secondDigit += pow
}
}
squareSum := int64(firstDigit + secondDigit)
return squareSum
}
func digitSum(number int64) int64 {
var remainder, sumResult int64 = 0, 0
for number != 0 {
remainder = number % 10
sumResult += remainder
number /= 10
}
return sumResult
}
func isPrime(num int64) bool {
if num < 2 {
return false
}
for i := int64(2); i <= int64(math.Sqrt(float64(num))); i++ {
if num%i == 0 {
return false
}
}
return true
}
The script above is the best script that I can make right now, I understand that I do a lot of iterations, so when I try to submit it will always show "time out". So I want to learn from you and want to see if there is a simpler script so that it can be submitted.
Thank you,
Regards

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.

How to improve my function that rounds floats to nearest 10 if 2 digit number, 100 if 3 digit number etc

I am drawing bar charts and i've come across a tricky problem. How to programmatically set the max value for the y axis label depending on the max value for a given series. So if you had a bar with a value of 7, you might want the y axis to go up to 10
My approach is not ideal but works like this:
Get a number to round, like 829
Count the number of digits (3)
Use a loop to convert to a string of 0s ("000")
Add a 1 to the start of the string then convert to a float (1000)
Find the difference (1000 - 829 = 171)
Get the first digit of the difference (1) and then add that to the first digit of the float, with the remaining set to zero ("900"), then convert to a number (900)
This means that 725 will see a y axis max label number of 800, and 829 of 900
My code works, but I feel like it's a piece of crap with a hacky approach
I have to code for big numbers. For example, if the float I want to find the max value for is >10000 then take the first two digits, and add 1000 to it. If >100,000 add 10,000
How can I improve here? I'm a little stuck, is my idea of converting to strings even right?!
Full code here:
package main
import (
"fmt"
"strconv"
)
func main() {
myFloat := 899175.0
x := getMaxYAxisValueForChart(myFloat)
fmt.Println("The number to find the maximum value for is: ", myFloat)
fmt.Println("This should be the max value for the y axis: ", x)
}
func getMaxYAxisValueForChart(float float64) (YAxisMaximum float64) {
//Convert to string with no decimals
floatAsString := fmt.Sprintf("%.f", float)
//Get length of the string float
floatAsStringLength := len(floatAsString)
//For each digit in the string, make a zero-string
stringPowerTen := "0"
for i := 1; i < floatAsStringLength; i++ {
stringPowerTen += "0"
}
//Add a 1 to the 0 string to get the difference from the float
stringPowerTenWithOne := "1" + stringPowerTen
//Convert the number string to a float
convertStringPowerTenToFloat := ConvertStringsToFloat(stringPowerTenWithOne)
//Get the difference from the denominator from the numerator
difference := convertStringPowerTenToFloat - float
//We want to isolate the first digit to check how far the float is (100 is far from 1000) and then correct if so
floatAsStringDifference := fmt.Sprintf("%.f", difference)
runes := []rune(floatAsStringDifference)
floatAsStringDifferenceFirstDigit := string(runes[0])
//For the denominator we want to take away the difference that is rounded to the nearest ten, hundred etc
runes = []rune(stringPowerTen)
differenceLastDigitsAsString := ""
if difference < 10 {
differenceLastDigitsAsString = "1"
} else if difference < 30 && difference < 100 {
differenceLastDigitsAsString = "0"
} else {
differenceLastDigitsAsString = floatAsStringDifferenceFirstDigit + string(runes[1:])
}
//Convert the number difference string from total to a float
convertDifferenceStringPowerTenToFloat := ConvertStringsToFloat(differenceLastDigitsAsString)
YAxisMaximum = convertStringPowerTenToFloat - convertDifferenceStringPowerTenToFloat
//If float is less than 10,0000
if float < 10000 && (YAxisMaximum-float >= 500) {
YAxisMaximum = YAxisMaximum - 500
}
if float < 10000 && (YAxisMaximum-float < 500) {
YAxisMaximum = YAxisMaximum
}
//If number bigger than 10,000 then get the nearest 1,000
if float > 10000 {
runes = []rune(floatAsString)
floatAsString = string(runes[0:2])
runes = []rune(stringPowerTen)
stringPowerTen = string(runes[2:])
runes = []rune(stringPowerTenWithOne)
stringPowerTenWithOne = string(runes[0:(len(stringPowerTenWithOne) - 2)])
YAxisMaximum = ConvertStringsToFloat(floatAsString+stringPowerTen) + ConvertStringsToFloat(stringPowerTenWithOne)
}
if float > 10000 {
runes = []rune(floatAsString)
floatAsString = string(runes[0:2])
runes = []rune(stringPowerTen)
stringPowerTen = string(runes[:])
runes = []rune(stringPowerTenWithOne)
stringPowerTenWithOne = string(runes[0:(len(stringPowerTenWithOne))])
YAxisMaximum = ConvertStringsToFloat(floatAsString+stringPowerTen) + ConvertStringsToFloat(stringPowerTenWithOne)
}
return YAxisMaximum
}
func ConvertStringsToFloat(stringToConvert string) (floatOutput float64) {
floatOutput, Error := strconv.ParseFloat(stringToConvert, 64)
if Error != nil {
fmt.Println(Error)
}
return floatOutput
}
Here is the solution based off of Matt Timmermans answer, but converted to work in Go:
func testing(float float64) (YAxisMaximum float64) {
place := 1.0
for float >= place*10.0 {
place *= 10.0
}
return math.Ceil(float/place) * place
}
Wow, that's a pretty complicated procedure you have. This is how I would do it if the numbers aren't enormous. I don't know go, so I'm going to guess about how to write it in that language:
func getMaxYAxisValueForChart(float float64) {
place := 1.0;
while float >= place*10.0 {
place *= 10.0;
}
return math.Ceil(float/place) * place;
}
You can get the magnitude of a number using Math.Log10
int magnitude = (int)Math.Pow(10, (int)Math.Log10(value));
Use that to divide the number down, calculate ceiling and then scale it back up.
No strings, no while loops.
Take the length of the string and calculate that 10 to the power of that length
Or...better take the Log base 10, get the integer part, add 1 and then return that to the power of 10 :)
import (
"fmt"
"math"
)
//func PowerScale(x int) int64{
// return int64(math.Pow(10,float64(len((fmt.Sprintf("%d",x))))))
//}
func PowerScale(x int) int64 {
return int64(math.Pow(10,float64(int(math.Log10(float64(x))+1))))
}
func main() {
fmt.Println(PowerScale(829))
fmt.Println(PowerScale(7))
}
Since 829 is an int, or can be cast to, a pure integer solution :
func getMaxYAxisValueForChart(int int64) {
base := 10;
while int > base*10 {
base := 10 * base;
}
return int + (base - int) % base;
}

How does one count a number of iterations with Go?

So I have this small piece of code that iterates as long as needed until the difference between the value sought after is abysmal. I want to count and print the number of iterations after the code is done running and preferably in my main function (along with printing everything else I need).
Edit: Okay, I've managed to do it like this. I wonder if there's an easier way of counting the iterations and passing them to the output function.
func sqrt(x float64) (float64, int) {
k := 1
z := 1.0
q := (z*z - x)/(2*z)
for {
if math.Abs(-q) > 0.001 {
z -= q
q = (z*z - x)/(2*z)
k += 1
} else {
break
}
}
return z, k
}
func main() {
k := 1
z := 1.0
z, k = sqrt(9)
fmt.Println("Your sqrt = ", z)
fmt.Println("Math Sqrt = ",math.Sqrt(9))
fmt.Println("Iterations: ", k)
}
You can return your float value and an int (as the number of iterations). I made very minor revision to your example to demonstrate.
func sqrt(x float64) (float64, int) {
z := 1.0
i := 1
q := (z*z - x) / (2 * z)
for {
if math.Abs(-q) > 0.01 {
i++
z -= q
q = (z*z - x) / (2 * z)
} else {
break
}
}
return z, i
}
func main() {
f, i := sqrt(9)
fmt.Printf("result: %f iterations: %d\n", f, i)
fmt.Println(math.Sqrt(9))
}
You can provide multiple return values through your function:
func main() {
numLoops, newNum := sqrt(9)
}
func sqrt(x float64) (int, float64) {
<implementation>
}
GoPlay here: https://play.golang.org/p/R2lV41EbEd

Resources