Hello, I am making a code which requires me to cycle between turn ratios 'n' from .01 all the way to 2.0 in .01 increments showing the Power Delivered at each new point. I have that part working fine.
However I do not know how to choose the best Turn ratio that gives the largest Power Delivered.
Essentially, I can find the Highest Power Delivered but I cannot get it to show what Ratio that power is on (the answer is .63)
instead if I cout an n value, it shows my ratio as 2.0 which is the largest ratio value (as a number).
any help? and can this be done with a nested for loop?
#include "stdafx.h"
#include <iostream>
usingnamespace std;
constdouble Vs = 40;
constdouble Ro = 20;
constdouble Rs = 8;
constdouble two = 2.0;
constdouble one = .01;
int _tmain(int argc, _TCHAR* argv[])
{
double Ps=0, n, largest=0, largestn=0;
for (n= one; n<=two + one; n+= one){
Ps = Rs*(((n*Vs)/(((n*n)*Ro)+Rs))*((n*Vs)/(((n*n)*Ro)+Rs)));
cout<<"At Turn Ratio: "<<n;
cout<<" Power delivered: "<<Ps<<endl;
if (Ps>largest)
largest=Ps;
}
cout<<endl<<"Turn Ratio Providing Maximum Power: "<<largest<<endl;
return 0;
}
i do know also that my final cout is set to largest which is set equal to power delivered, but if I change it to n (Turn ratio) it still only shows the largest ratio
By the way, this expression has a lot of unnecessary brackets, which don't affect the result, but make it hard to read: Ps = Rs*(((n*Vs)/(((n*n)*Ro)+Rs))*((n*Vs)/(((n*n)*Ro)+Rs)));
It might be simplified like this: Ps = Rs * n*Vs / (n*n*Ro + Rs) * n*Vs / (n*n*Ro + Rs);
Or since there is a squared term, either use the pow() function, or an intermediate variable like this:
constdouble two = 2.0;
constdouble one = .01;
int _tmain(int argc, _TCHAR* argv[])
{
double Ps=0, n, largest=0, largestn=0;
for (n= one; n<=two + one; n+= one){
Never use doubles in for loop conditions.
It is much better to use ints, and cast them to doubles inside the loop.
Doubles will fail in the equality or less than test because of their binary fraction representation, so not all real numbers can be represented. This fails:
1 2
float a =0.1; //a == 0.0999997
if (1.0 == 10 * a) //fail - 10 * a == 0.9999997
The same thing will happen in a for loop. Changing the type to double doesn't help.
if (Ps>largest)
The same problem here. Investigate the use of numeric_limits<double>epslon
An epsilon value needs to be scaled up to the number you are using.
To compare doubles, you need to compare the absolute value of the difference between your number and the one being compared to, with the scaled up epsilon
wow thanks guys for pointing me to these things. I had no idea about the doubles in a loop possibly causing problems. And right order of operations for the formula. the parenthesis always throw me off.