 There's more than one way to do things PerlMonks

Re: Exponential Function Programming

by okram (Monk)
 on Nov 22, 2007 at 15:44 UTC ( #652398=note: print w/replies, xml ) Need Help??

in reply to Exponential Function Programming

# exp. \$n = 2; \$e_n = exp(\$n); print "e^\$n = \$e_n\n"; sub my_factorial { my \$n = shift; my \$s=1; my \$r=1; while (\$s <= \$n) { \$r *= \$s; \$s++; } if(\$n == 0) { \$r=0; } return \$r; } sub my_exp_x { my \$x = shift; my \$max_iterations = shift; my \$result = 1 + \$x; my \$i = 2; while (\$i < \$max_iterations) { \$result += (\$x ** (\$i)) / (my_factorial(\$i)); \$i++; } return \$result; } print "test: ", my_exp_x(\$n,1000);

Replies are listed 'Best First'.
Re^2: Exponential Function Programming
by Dominus (Parson) on Nov 23, 2007 at 19:45 UTC
sub my_factorial { ... if(\$n == 0) { \$r=0; } return \$r; }
Your function says that 0 factorial is 0. But it's not; it's 1.

Perl 6 is very generous in this:

pugs> sub postfix:<!> (Int \$n) { [*] 1..\$n } undef pugs> say \$_! for ^10 1 1 2 6 24 120 720 5040 40320 362880 undef

(I personally believe that I've posted this before here and in different media, but that's jut because it's quite about the only thing I can actually do in pugs ATM.)

Re^2: Exponential Function Programming
by Abulil on Nov 22, 2007 at 15:57 UTC
i got your program but what im looking for is how to do the basic function as it is for example i need to do X to the power of N, then divide it by N factorial and at the end add them all from (1 until the N number i entered) Thanks alot
x to the power of n is done via: \$x ** \$n or
sub x_power_n { my \$x = shift; my \$n = shift; my \$result = \$x; my \$i = 1; while (\$i < \$n) { \$result *= \$x; \$i++; } return \$result; }
You need to do this, though, "infinite" times, reason why I provided a parameter to "stop" after a certain time.

That only works for integer exponents. The equation in the OP handles real numbers.

Using exp and ln, it's possible to find any exponent.

A reply falls below the community's threshold of quality. You may see it by logging in.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://652398]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2022-01-29 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In 2022, my preferred method to securely store passwords is:

Results (74 votes). Check out past polls.

Notices?