Evaluation of Risk in Investments | Java code for above approach ; Vector stores the observation in pairs of format ( xi , fi ) , where xi = value of observation ; Function to calculate the summation of fi * xi ; Function to calculate summation fi ; Function to calculate the mean of the set of observations v ; Function to calculate the std deviation of set of observations v ; Get sum of frequencies ; Get the mean of the set of observations ; Driver Code
import java . util . * ; class GFG { static class pair { float first , second ; public pair ( float first , float second ) { this . first = first ; this . second = second ; } } static Vector < pair > Vector ; static float sigma_fx ( pair [ ] a ) { float sum = 0 ; for ( pair i : a ) { sum += i . first * i . second ; } return sum ; } static float sigma_f ( pair [ ] a ) { float sum = 0.0f ; for ( pair i : a ) { sum += i . second ; } return sum ; } static float calculate_mean ( pair [ ] a ) { return sigma_fx ( a ) / sigma_f ( a ) ; } static float calculate_std ( pair [ ] a ) { float f = sigma_f ( a ) ; float mean = sigma_fx ( a ) / f ; float sum = 0 ; for ( pair i : a ) { sum += ( i . first - mean ) * ( i . first - mean ) * i . second ; } return ( float ) Math . sqrt ( sum / f ) ; } public static void main ( String [ ] args ) { pair [ ] A = { new pair ( 0f , 0.1f ) , new pair ( 100f , 0.1f ) , new pair ( 200f , 0.2f ) , new pair ( 333f , 0.3f ) , new pair ( 400f , 0.3f ) } ; pair [ ] B = { new pair ( 100f , 0.1f ) , new pair ( 200f , 0.5f ) , new pair ( 700f , 0.4f ) } ; float avg_A = calculate_mean ( A ) ; float avg_B = calculate_mean ( B ) ; float std_A = calculate_std ( A ) ; float std_B = calculate_std ( B ) ; System . out . print ( " For ▁ Investment ▁ A " + "NEW_LINE"); System . out . print ( " Average : ▁ " + avg_A + "NEW_LINE"); System . out . print ( " Standard ▁ Deviation : ▁ " + std_A + "NEW_LINE"); System . out . print ( " Normalised ▁ Std : ▁ " + std_A / avg_A + "NEW_LINE"); System . out . print ( " For ▁ Investment ▁ B " + "NEW_LINE"); System . out . print ( " Average : ▁ " + avg_B + "NEW_LINE"); System . out . print ( " Standard ▁ Deviation : ▁ " + std_B + "NEW_LINE"); System . out . print ( " Normalised ▁ Std : ▁ " + std_B / avg_B + "NEW_LINE"); if ( ( std_B / avg_B ) < ( std_A / avg_A ) ) System . out . print ( "Investment B is less riskyNEW_LINE"); else System . out . print ( "Investment A is less riskyNEW_LINE"); } }