Re: Fractional Exponents in Delphi

 Posted by webmaster Guido In Reply to: Fractional Exponents posted by Lionel : Using the following Delphi code I get the results I want but I have not been able to get a fractional exponent such as 1/2 or 1/3 to work. If I use 0.5 or 0.33333 as an exponent in the [exp(Y*ln(X)] formular I get the square root and cube root with no problems but what if I wanted to use 1/8 as an exponent? would I have to use 0.1250 instead? The following code is what I am using but I have not had much luck trying to use a fraction in EditBox2. Is there a simple solution to this dilemma? : Var X, Y, Result : Variant; : Begin: X:=Edit1.Text; //Input X: YL=Edit2.Text; //Input Y : Result:=exp(Y*ln(X));: Edit3.Text:=(FloatToStrF(Result,ffFixed,8,8)); : end;----------------------------------------------- Note that there is an easier Delphi function: Power(Base, Exponent). Because in some Delphi versions this function is in Delphi's MATH unit, you have to add MATH to the USES statement of your unit. Let's look at some sample code with a couple of Edit-boxes:procedure TForm1.btnPowerClick(Sender: TObject); var N, P, R: real; ErrCode1, ErrCode2: integer; begin Val(Edit1.Text, N, ErrCode1); Val(Edit2.Text, P, ErrCode2); if (ErrCode1 = 0) and (ErrCode2 = 0) then begin R := Power(N, P); Edit3.Text := FloatToStr(R); end else ShowMessage('Invalid number'); end; For a fractional exponent like 1/8 you have to enter 0.125 in Edit2. You can not simply enter the text 1/8 because the procedure Val() would fail.If you want to enter the exponent in the form of a fraction like 1/8 then you need some more code to convert the text '1/8' to the number 0.125Let's give it a try: procedure TForm1.btnPowerClick(Sender: TObject); var N, P1, P2, P, R: real; ErrCode1, ErrCode2, ErrCode3, SlashPos: integer; begin Val(Edit1.Text, N, ErrCode1); SlashPos := Pos('/', Edit2.Text); ErrCode3 := 0; if SlashPos > 0 then begin // there is a / in the edit box Val(Copy(Edit2.Text,1,SlashPos-1), P1, ErrCode2); Val(Copy(Edit2.Text,SlashPos+1,Length(Edit2.Text)), P2, ErrCode3); P := P1 / P2; end else // there is no / in the edit box Val(Edit2.Text, P, ErrCode2); if ErrCode1 + ErrCode2 + ErrCode3 = 0 then begin R := Power(N, P); Edit3.Text := FloatToStr(R); end else ShowMessage('Invalid number'); end; I tested it, and oh miracle ;-) it worked. Please, let me know if this is what you wanted. Find related articles Re:Re: Fractional Exponents in Delphi Lionel Joyner 1/10/2004 Delphi Forum :: Related Articles and Replies :: Post Followup