首页 > 代码库 > Little Pony and Expected Maximum
Little Pony and Expected Maximum
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains mdots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.
Input
A single line contains two integers m and n (1 ≤ m, n ≤ 105).
Output
Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn‘t exceed 10 - 4.
题目大意是一个m面的骰子,掷N次,求n次中最大值的期望。
那么根据数学,期望=每种情况发生概率*最大点数。对于每种情况的概率这里采用从反面计算的方法:如果掷出最大值为i的情况,那么情况数:
pow(i,n)-pow(i-1,n)【这里自己好好体会下】。概率即为情况数除以总情况数pow(m,n)。 化简后即为pow(i/m,n)-pow((i-1)/m,n)。程序中实现采用了更为简洁的表现方法。这样,将每次的计算结果记入ans,最后按题意输出就行了。
#include<iostream>#include<cstdio>#include<cmath>using namespace std;int main(){ double n=0,m=0; cin >> m >> n; double t=0,l=0,ans=0; for (int i=1;i<=m;++i){ t=pow((i*1.0)/m,n); ans+=(t-l)*i; l=t; } printf("%.12f\n",ans); return 0; }