Kotlin - How can a math function be graphically pl

2019-12-16 20:16发布

问题:

I have the following function, well it is the formula of the normal distribution and my goal is to graph it using the GraphView library. Well, I have the following:

  • Id -- plot

code kotlin

class ExampleActivity : AppCompatActivity() {
    lateinit var series1: LineGraphSeries<DataPoint>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_example)

        series1 = LineGraphSeries<DataPoint>()

        val media = 8.0  
        val sd = 2.0  

        fun linspace(start: Double, stop: Double, num: Int) = Array(num) { start + it * ((stop - start) / (num - 1)) }

        val x1 = linspace(media - 3*sd, media + 3*sd, 10)
        val normal = NormalDistribution(media,sd)

        for (i in x1){
            val y = normal.cumulativeProbability(i)
            series1.appendData(DataPoint(i,y),false,x1.size)
        }
        plot.viewport.isXAxisBoundsManual = true
        plot.viewport.setMaxX(20.0)
        plot.viewport.isYAxisBoundsManual = true
        plot.viewport.setMaxY(2.0)
        //plot.viewport.isScalable = true
        plot.addSeries(series1)
    }
}

result

this is very strange, in python I used the same and the result is more complete, I show you.

code python

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 8
sigma = 2
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 10)
print(np.linspace(mu - 3*sigma, mu + 3*sigma, 10))
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

result python

Info

code kotlin val x1 = linspace(media - 3*sd, media + 3*sd, 10)

==

code Python x = np.linspace(mu - 3*sigma, mu + 3*sigma, 10)

Can you help me please, what do I need to add?

回答1:

It looks like the python example is plotting the .pdf "probability density function" while the kotlin example is plotting the .cumulativeProbability which is essentially the integral of the PDF. Most likely you'll want to use the .density method instead.