How to build in degree in pascal

How to build in degree in pascal

The programming language Pascal differs from most of others in the fact that in it there is no operator of exponentiation. Therefore the fragment of the program for implementation of this mathematical operation should be made independently.

Instruction

1. The simplest case arises when the number needs to be built in small whole positive degree. Such mathematical operation can be performed literally for one line. For example, if the number needs to be built always in the fourth degree, use such line: b:=a*a*a*a; Variables an and b have to have the type corresponding to the range and a type of the numbers which are exposed to exponentiation.

2. If the number is also built in the whole and positive degree, but it is big, and, besides, can change, use a cycle. For this purpose place such fragment in the program: c:=a; if b=0 then c: =1; if b> =2 then for i: =2 to b do c: =a*c; Here an is the number which is subject to exponentiation, b is an exponent, with - result. Variables i and b - surely the integer type.

3. To build number in fractional degree, use properties of logarithms. The corresponding fragment of the program at the same time will look so: c:=exp(b*ln(a)); This way does not allow to work with zero and negative numbers. For elimination of the first of these shortcomings use such design: if a=0 then c: =1 else c: =exp(b*ln(a)); It will allow to bypass restriction for the range of values of input parameter of a natural logarithm which at zero does not make mathematical sense. The second shortcoming, however, will remain in force: it will not be possible to build in degree negative numbers still. Use all variables like real.

4. To build a negative number in degree, take its module, substitute in the previous expression then change the sign of result. In language the Pascal it will look as follows: c: (-1) *exp (b*ln(abs(a))); Then, if degree is even, take the module from result: if round(b/2) =b/2 then c: =abs(c);

5. Sometimes there is a need for the universal fragment of the program allowing to carry out exponentiation concerning any numbers. Then make it as follows: c: =0; if a0 then c: =exp(b*ln(a)); if b=0 then c: =1; if round(b/2) =b/2 then c: =abs(c); Here all variables - also like real.

Author: «MirrorInfo» Dream Team


Print