Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Function that calculates e^x

Tags:

Implement a function that calculates the value of e ^ x, x is a parameter of the function, an integer. To do this, use the Taylor series expansion to calculate the potency of e. The function will receives as a parameter, in addition to the exponent x, the number of terms of the series, which will operate as a maximum value of n. For the resolution of this function, recursion must be used.

I made this:

factorial 0 = 1
factorial n = n * factorial (n-1)

consigna3::Int->Int->Float
consigna3 _ 0 = 1
consigna3 x n = (fromIntegral(x^n) / fromIntegral(factorial n)) + consigna3 x (n-1)

But some results are wrong, this is what I expected:

Ejemplo 1: Main> funcion3 1 1
           2.0
Ejemplo 2: Main> funcion3 1 10
           2.718282
Ejemplo 3: Main> funcion3 2 10
           7.388997
Ejemplo 4: Main> funcion3 10 20
           21991.48
Ejemplo 5: Main> funcion3 10 30
           22026.46
Ejemplo 6: Main> funcion3 0 30
           1.0

The results (10 20) and (10 30) do not match what the function I did returns. What I am doing wrong? Thanks and sorry for my English.

like image 460
Ignacio Mauricio Rios Avatar asked Oct 09 '20 14:10

Ignacio Mauricio Rios


People also ask

How do you write exponents in Haskell?

There are three two-argument exponentiation operations: ( ^ ) raises any number to a nonnegative integer power, ( ^^ ) raises a fractional number to any integer power, and ( ** ) takes two floating-point arguments. The value of x^0 or x^^0 is 1 for any x , including zero; 0**y is undefined.

How do you define a function in Haskell?

The most basic way of defining a function in Haskell is to ``declare'' what it does. For example, we can write: double :: Int -> Int double n = 2*n. Here, the first line specifies the type of the function and the second line tells us how the output of double depends on its input.

Which of the following is a factorial function in Haskell?

Factorial in Haskell definition of factorial function, which takes one argument of Integer type (integer number of unlimited precision) and returns the same type. The function is defined recursively, and types of argument and return are given explicitly to avoid ambiguity. printf command is the same as in C++.


1 Answers

You are using Int for calculations that will overflow an Int. Instead, convert to Float right away, and then using Float for everything. So:

consigna3 x n = ((fromIntegral x)^n / factorial (fromIntegral n)) + consigna3 x (n-1)

There are two critical changes from Int to Float here: first, you do x^n where x :: Int, but I do fromIntegral x^n where fromIntegral x :: Float; second, you do factorial n where n :: Int, but I do factorial (fromIntegral n) where fromIntegral n :: Float.

like image 192
Daniel Wagner Avatar answered Sep 30 '22 18:09

Daniel Wagner