How can I get the value of a T-student distribution? - kotlin

I have been reviewing the documentation of apache commons math and I find that it also calculates distributions, but I can not understand how it works.
I have two values
degrees of freedom = 13
confidence interval = 0.95
My problem is that it does not yield the value I need,
The objective is:
result = 1.771
import org.apache.commons.math3.distribution.TDistribution
fun calculo(a:Double, b:Double): Double {
val distf = TDistribution(a,b)
return distf.getNumericalMean()
}
fun main(args: Array<String>) {
val ko = calculo(13,0.95)
println(ko)
}
```

You can use the following:
new org.apache.commons.math3.distribution.TDistribution(deg_freedom).
inverseCumulativeProbability(probability)
Where deg_freedom=13, and probability=0.95.

Related

Bmi calculator kotlin

I'm in the process of learning android studio and kotlin. I have no experience with java so while learning kotlin I'm only drawing on experience I have from C# programming. I am trying to make a simple script which takes the input from the text field of height and weight take them and put them into a formula that gives the BMI score which is then printed everything works when I tested the script by simply multiply or adding height and weight together to test so I know the general code works. How can I fix my problem atm the output Is always 0 I've messed around using values much larger and it appears to not be multiplying by 10,000 at the end any fixes guys? thanks.
package com.example.test
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnChangeText = findViewById(R.id.btn_change_text) as Button
val tvBMI = findViewById(R.id.output_BMI) as TextView
val weight = findViewById(R.id.input_weight) as EditText
val height = findViewById(R.id.input_height) as EditText
btnChangeText.setOnClickListener {
val bmiWeight = weight.text.toString().toInt()
val bmiHeight = height.text.toString().toInt()
val bmiCalc = bmiWeight / bmiHeight / bmiHeight * 10000
tvBMI.text = bmiCalc.toString()
}
}
}
Looks like bmiWeight and bmiHeight are integers. Integer division results in a chopping off of the remainder or simply 0 if the denominator is larger.
Try:
bmiWeight.toDouble() / bmiHeight / bmiHeight * 10000
or get bmiHeight and bmiWeight as a double to begin with
val bmiWeight = weight.text.toString().toDouble()

Show or hide decimals

I have a double value, if that number is like this: 123.00 I need to show it as 123 only, without decimal places, but, if the number is like 123.23 or 123.2, I need to show it with the present decimal places: 123.23 or 123.2, as the case may be.
I have tried with decimal format but I couldn't find the right pattern.
It is a better way to do this than a string conversion and operate with substrings and things like that?
DecimalFormat is what you're looking for I think:
import java.text.DecimalFormat
fun main(args : Array<String>) {
val df = DecimalFormat("0.##")
println(df.format(123.0))
println(df.format(123.3))
println(df.format(123.32))
println(df.format(123.327))
}
Output:
123
123.3
123.32
123.33
Here's one way you could do it:
fun func(x: Double): String {
if (x.rem(1).compareTo(0) == 0){
return x.toInt().toString();
} else {
return x.toString();
}
}
print(func(1.32132)); //Returns 1.32132
print(func(3.00)); //Returns 3
You could use DecimalFormat with setMaximumFractionDigits. Creating an extension function would keep the complexity away from the call-site:
fun Double.toStringRounded(fracDigits: Int) = DecimalFormat().apply {
setMaximumFractionDigits(fracDigits)
}.format(this)
Usage:
3.14159.toStringRounded(2) // will be "3.14"

Traveling salesman with random initial solution, optimization algorithm returning unexpected result

I know traveling salesman is well known, but I need some help on why my optimization algorithm is returning an unexpected result. I have created an initial solution by selecting cities in a random order. I have also created a class with a constructor with the distance matrix and initial solution as parameters. The optimization algorithm is very simple; it swaps two cities and checks if the route distance has been improved, and if it has improved the best solution should be updated. This goes on for 6 iterations. The problem is that the it seems like the best solution is updated and overwritten even if the condition for overwriting it is not met. I will add an image showing the results from a test run.
It seems like the variable bestSolution is overwritten but not bestDistance. I must have some sort of tunnel vision, because I can't figure this one out even if the code is really simple. Can someone please chime in why bestSolution is overwritten and returned with unexpected result?
Code example below:
package RandomMethod
import GreedyHeuristic
import java.util.*
fun main(args: Array<String>) {
/*A B C*/
val distances = arrayOf(/*A*/ intArrayOf(0, 2, 7),
/*B*/ intArrayOf(2, 0, 9),
/*C*/ intArrayOf(7, 9, 0))
val initalSolution = findRandomRoute(distances)
println("Initial solution: $initalSolution")
println("Total distance: ${findTotalDistance(distances, initalSolution)}\n")
val optimizedSolution = GreedyHeuristic(distances, initalSolution).optimize()
println("\nOptimized solution with Greedy Heuristic: $optimizedSolution")
println("Total distance: ${findTotalDistance(distances, optimizedSolution)}")
}
fun areAllCitiesVisited(isCityVisited: Array<Boolean>): Boolean {
for (visited in isCityVisited) {
if (!visited) return false
}
return true
}
fun findTotalDistance(distances: Array<IntArray>, orderToBeVisited: MutableList<Int>): Int {
var totalDistance = 0
for (i in 0..orderToBeVisited.size - 2) {
val fromCityIndex = orderToBeVisited.get(i)
val toCityIndex = orderToBeVisited.get(i + 1)
totalDistance += distances[fromCityIndex].get(toCityIndex)
}
return totalDistance
}
fun findRandomRoute(distances: Array<IntArray>): MutableList<Int> {
val visitedCities: Array<Boolean> = Array(distances.size, {i -> false})
// Find starting city index. 0 = A, 1 = B, 2 = C .... N = X
var currentCity = Random().nextInt(distances.size)
val orderToBeVisited: MutableList<Int> = mutableListOf(currentCity)
visitedCities[currentCity] = true
while (!areAllCitiesVisited(visitedCities)) {
currentCity = Random().nextInt(distances.size)
if (!visitedCities[currentCity]) {
orderToBeVisited.add(currentCity)
visitedCities[currentCity] = true
}
}
return orderToBeVisited
}
And the class for optimization:
import java.util.*
class GreedyHeuristic(distances: Array<IntArray>, initialSoltion: MutableList<Int>) {
val mInitialSolution: MutableList<Int> = initialSoltion
val mDistances: Array<IntArray> = distances
fun optimize(): MutableList<Int> {
var bestSolution = mInitialSolution
var newSolution = mInitialSolution
var bestDistance = findTotalDistance(mDistances, bestSolution)
var i = 0
while (i <= 5) {
println("best distance at start of loop: $bestDistance")
var cityIndex1 = Integer.MAX_VALUE
var cityIndex2 = Integer.MAX_VALUE
while (cityIndex1 == cityIndex2) {
cityIndex1 = Random().nextInt(mInitialSolution.size)
cityIndex2 = Random().nextInt(mInitialSolution.size)
}
val temp = newSolution.get(cityIndex1)
newSolution.set(cityIndex1, newSolution.get(cityIndex2))
newSolution.set(cityIndex2, temp)
val newDistance: Int = findTotalDistance(mDistances, newSolution)
println("new distance: $newDistance\n")
if (newDistance < bestDistance) {
println("New values gived to solution and distance")
bestSolution = newSolution
bestDistance = newDistance
}
i++
}
println("The distance of the best solution ${findTotalDistance(mDistances, bestSolution)}")
return bestSolution
}
fun findTotalDistance(distances: Array<IntArray>, orderToBeVisited: MutableList<Int>): Int {
var totalDistance = 0
for (i in 0..orderToBeVisited.size - 2) {
val fromCityIndex = orderToBeVisited.get(i)
val toCityIndex = orderToBeVisited.get(i + 1)
totalDistance += distances[fromCityIndex].get(toCityIndex)
}
return totalDistance
}
}
Kotlin (and JVM languages in general) doesn't copy values unless you specifically ask it to. This means that, when you do this:
var bestSolution = mInitialSolution
var newSolution = mInitialSolution
You're not setting bestSolution and newSolution to separate copies of mInitialSolution, but rather making them point at same MutableList, so mutating one mutates the other. Which is to say: your problem isn't that bestSolution is getting overwritten, it's that you're accidentally modifying it every time you modify newSolution.
You then reuse newSolution for every iteration of your while loop without ever creating a new list. This leads us to two things:
Because newSolution still aliases bestSolution, modifying the former also modifies the latter.
bestSolution = newSolution doesn't do anything.
As mentioned in a comment, the easiest way to fix this is by making strategic use of .toMutableList(), which will force copying the list.You can achieve this by making this change at the top:
var bestSolution = mInitialSolution.toMutableList()
var newSolution = mInitialSolution.toMutableList()
Then inside the loop:
bestSolution = newSolution.toMutableList()
Incidentally: As a general rule, you should probably return and accept List rather than MutableList unless you specifically want it to be part of the contract of your function that you're going to mutate things in-place. In this particular case, It would've forced you to either do something icky (like unsafe-casting mInitialSolution to MutableList, which should sound all sorts of warning bells in your head), or copy the list (which would've nudged you towards the right answer)

Kotlin Long to Float difference

I am trying to convert Long value to Float in Kotlin. However I am seeing it is changing the value by a small fraction.
Here's a simple test run:
import java.text.DecimalFormat
fun main(args: Array<String>) {
val l = 1513741500
val f:Float = l.toFloat()
val df = DecimalFormat("0")
println(df.format(f))
}
Output:
1513741440
As can be seen there is a slight difference between the values. How can I ensure the same value is returned on conversion?
l: Int = 1513741500
f: Float = 1.51374144E9
d: Double = 1.5137415E9
So if you plan to use large numbers, rather use Double than Float.

How to convert toFixed(2) in Kotlin

What should I write in the place of area.toFixed(2)
fun main(args: Array<String>) {
val a = 20
val h = 30
val area = a * h / 2
println("Triangle area = ${area.toFixed(2)}")
}
I think you really meet a problem that how to convert Javascript code to Kotlin code. You need to ask the question clearly at next time, :). you can use String#format instead, for example:
println("%.2f".format(1.0)) // print "1.00"
println("%.2f".format(1.253)) // print "1.25"
println("%.2f".format(1.255)) // print "1.26"
AND the area is an Int which means it will truncates the precision, Kotlin doesn't like as Javascript use the numeric by default, so you should let a*h divide by a Double, then your code is like as below:
// v--- use a `Double` instead
val area = a * h / 2.0
println("Triangle area = ${"%.2f".format(area)}")