Python maths – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 08:53:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python maths – Java2Blog https://java2blog.com 32 32 Convert Roman Number to Integer in Python https://java2blog.com/convert-roman-number-to-integer-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-roman-number-to-integer-python https://java2blog.com/convert-roman-number-to-integer-python/#respond Sat, 25 Jun 2022 10:14:29 +0000 https://java2blog.com/?p=20371 In this post, we will see how to convert roman number to integer in python.

How to Convert Roman Number to Integer in Python

There are multiple ways in which numbers can be represented in the world of Python programming. Roman literals are one such approach to representing numbers in Python. Often times there is a need to convert one type of representation to another for the purpose of simplifying calculations and to allow ease of using several functions on the data.

This tutorial demonstrates the different ways available to convert roman number to integer in python.

What is a roman number in Python?

Roman literals follow the same rules in Python as that in general mathematics. Let us quickly brush up on the characters utilized to represent the different numbers and the rules that need to be followed in accordance with naming.

The general naming convention associated with roman literals is given below, and the same will also be adhered to while making use of roman numbers in Python.

Numeral Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Moreover, the rules to keep in mind when representing roman literals as a number are mentioned below for a clearer understanding of the user.

  • The character I refers to the number 1 when utilized individually. It can only be utilized three times in one go. This means that the number 4 cannot be represented as IIII.
  • It can be utilized as a prefix to letters like V and X to denote numbers 4 and 9 respectively.
  • Similarly, the sign X, which is for the number 10 initially, when as a suffix to L and C makes it represent the numbers 60 and 110 respectively.
  • Similarly, the sign C, which is for the number 100 initially, when as a suffix to D and M makes it represent the numbers 600 and 1100 respectively.

Now that we have covered the generation of roman number denotations, let us move on to see the different approaches that can be utilized in completing the task of converting roman numbers to integers in python.

How to convert roman number to integer in python?

There are multiple ways of converting roman number to integer in Python, ranging from utilizing manually created user-defined functions to utilizing certain unpopular libraries, all of which will be explained in the article below.

Using the if...else statement to convert roman number to integer in Python.

The if...else statement is one of the simplest decision-making statements. It contains different blocks of code and a certain condition is tested to check whether the given block of code would get executed or not.

The following code uses the if...else statement to convert roman number to integer in Python.

def RL(x):
    if (x == 'I'):
        return 1
    if (x == 'V'):
        return 5
    if (x == 'X'):
        return 10
    if (x == 'L'):
        return 50
    if (x == 'C'):
        return 100
    if (x == 'D'):
        return 500
    if (x == 'M'):
        return 1000
    return -1
def RomtoInt(str):
    a = 0
    i = 0
    while (i < len(str)):
        x1 = RL(str[i])
        if (i + 1 < len(str)):
            x2 = RL(str[i + 1])
            if (x1 >= x2):
                a = a + x1
                i = i + 1
            else:
                a = a + x2 - x1
                i = i + 2
        else:
            a = a + x1
            i = i + 1
    return a
print(RomtoInt("CIV"))

The above code provides the following output:

104

Using classes and a dictionary to convert roman number to integer in Python.

Python is one of the most popular examples of Objected Oriented Programming (OOP) language out there, along with C++. Therefore, just like its rival, Python also supports and makes use of the concept of Classes. Almost every single thing that you see in a Python code can be deemed an object, along with its method and properties. Classes are just an approach or a blueprint to create these objects in Python.

Along with the use of classes, we will also utilize a Dictionary. A dictionary is one of the four pre-defined data types in Python that can be utilized to store data. A dictionary usually takes in the data in the form of key:value pairs, which makes it excellent for storing the data on the conversion of roman literals to integers.

The following code makes use of classes and a dictionary to convert roman number to integer in Python.

class sol:
    def RomtoInt(self, s):
        x = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        y = 0
        for i in range(len(s)):
            if i > 0 and x[s[i]] > x[s[i - 1]]:
                y += x[s[i]] - 2 * x[s[i - 1]]
            else:
                y += x[s[i]]
        return y
print(sol().RomtoInt('CIV'))

The above code provides the following output:

104

Using the roman module to convert roman number to integer in Python.

Some newer versions of Python 3 support the roman module that provides functions that smoothen the process of conversion between roman numbers and other data types.

The roman module first needs to be installed in the system and then can be simply imported to the code which grants us access to the functions provided by this module. This module can simply be installed with the pip command.

pip install roman

After installing the roman module, we can move on to implementing the functions of this module to achieve the task at hand. For this, we will make use of the roman.fromRoman() function.

The following code uses the roman module to convert roman number to integer in Python.

import roman
x=roman.fromRoman("CIV")
print(x)

The above code provides the following output:

104

It is important to note that this function is accurate in converting roman numbers to integer with the value varying between 0-5000. When it comes to numbers higher than that, then the accuracy of this function might dip down. In those cases, it is best to create a user-defined function and implement that.

Conclusion

This tutorial brushes up on the concept of roman numbers in Python and emphasizes providing a detailed explanation of the different ways available to convert roman number to integer in Python.

The article takes three unique approaches to implement the task given at hand, with two of those having to create a user-defined function, and the third using a straight-up module inherited function. In case of the value of numbers is too high, it is always recommended to create user-defined functions and implement them instead of depending on functions from the roman library.

]]>
https://java2blog.com/convert-roman-number-to-integer-python/feed/ 0
Spectrogram in Python https://java2blog.com/spectrogram-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=spectrogram-in-python https://java2blog.com/spectrogram-in-python/#respond Thu, 16 Sep 2021 19:08:01 +0000 https://java2blog.com/?p=16567 Spectrogram

A spectrogram is a wave-like graph which is used to represent measures like loudness, frequencies, and other signals that change over time. With the help of a spectrogram, these signals and measures are visually more understandable. A spectrogram is a two-dimensional graph in which the time component is represented mostly on the x-axis.

In Python, plotting a spectrogram is a part of data visualisation and can be done using various libraries.

In this tutorial, we will see how to plot a spectrogram in Python using different dictionaries.

Plotting Spectrogram using the matplotlib.pyplot.specgram function of the Matplotlib Library.

The Matplotlib library is a very good library when it comes to data visualisation in python. With the help of this library, many types of graphs and visual representations of the data can be made in Python.

In this method, the matplotlib.pyplot.specgram function is used to plot the spectrogram. This function has various parameters. Some of them are:

  • x (1-D array) – This parameter defines the data of which the spectrogram has to be made.
  • Fs (float) – This parameter helps in calculating the fourier frequencies, i.e, cycles of the samples per unit time. The default value of this parameter is 2.
  • sides – This parameter defines which sides of the whole spectrum are to be returned. The default is one-sided for real data and two-sided for complex data. onesided forces that the spectrum returned is one-sided and twosided forces two-sided spectrum.
  • noverlap (int) – This parameter defines the number of points of overlap between the blocks in the spectrum. The default value of this parameter is 128.

There are many other parameters in this function such as pad_to, NFFT, detrend, etc. Also, note that all the parameters except the x (1-D array) parameter are not necessary to define, i.e, they are optional.

Example:

import numpy as np
import matplotlib.pyplot as plt 
dt=0.0001
w=2
t=np.linspace(0,5,math.ceil(5/dt))
A=30*(np.tan(5 * np.pi * t))
plt.specgram(A,Fs=1)
plt.title('Spectrogram Using Matplotlib Library')  
plt.show()

Output:

  • The program above creates a spectrogram for the function A=30tan(5*np.pi*t).
  • Note that in the program above, the linspace() function of the NumPy is used. The linspace() function helps in creating a random numerical sequences that are evenly spaced.

Plotting Spectrogram using the scipy.signal.spectrogram function of the SciPy Library

Python’s SciPy library is a module that is used for tasks like linear algebra, integration, image processing, and many more. It is an open source library that helps in performing both scientific and technical computing. The SciPy library is often used along with the NumPy library.

In this method, the scipy.signal.spectrogram function is used to plot a spectrogram. This function has various parameters. Some of them are:

  • x (1-D array) – This parameter defines the data of which the spectrogram has to be made.
  • Fs (float) – This parameter helps in calculating the fourier frequencies, i.e, cycles pf the samples per unit time. The default value of this parameter is 1.
  • nperseg (int) – This parameter is used to define the length of each segment. The default value of this parameter is None.
  • noverlap (int) – This parameter defines the number of points of overlap between the blocks in the spectrum. The default value of this parameter is None.
  • axis (int) – This parameter defines the axis along which the spectrogram is computed. The default value of this parameter is over the last axis, i.e, axis=-1.

There are many other parameters in this function such as nfft, scaling, detrend, etc. Also, note that all the parameters except the x (1-D array) parameter are not necessary to define, i.e, they are optional.

Example:

import math
import numpy as np
import matplotlib.pyplot as plt 
from scipy import signal
dt=0.0001
w=3
t=np.linspace(0,5,math.ceil(5/dt))
A=5*(np.cos(1 * np.pi *500* t))
f, t, Sxx = signal.spectrogram(A, fs=1, nfft=510)
plt.pcolormesh(t, f, Sxx)
plt.ylabel('Frequency')
plt.xlabel('Time')
plt.title('Spectrogram Using SciPy Library')
plt.show()

Output:

  • The program creates a spectrogram for the function A=5cos(500*np.pi*t).
  • Note that here also the linspace() function of the NumPy is used.
  • Here, the value of the fs parameter is set to 1 which will represent the sample frequency.
  • And the nfft is set to 510 which represents the length of the FFT being used.

That’s all about Spectogram in Python.

]]>
https://java2blog.com/spectrogram-in-python/feed/ 0
Inverse Sine in Python https://java2blog.com/inverse-sine-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=inverse-sine-in-python https://java2blog.com/inverse-sine-in-python/#respond Tue, 24 Aug 2021 15:34:11 +0000 https://java2blog.com/?p=16311 In Python, one can perform many kinds of tasks including mathematical operations like add, subtract, divide, dealing with matrices, etc. Besides all these operations, one can also perform complex mathematical operations like dealing with sets and matrices, trigonometric operations using many libraries and modules provided by Python.

In this tutorial, we will see how to find out the inverse sine in Python.

Use the numpy.arcsin Function of the NumPy Library

The NumPy library is a widely used library in Python. This library helps in dealing with arrays, matrices, linear algebra, and Fourier transform. NumPy stands for Numerical Python.

The NumPy has a function known as the arcsin() function that is a mathematical function used to calculate the inverse sine of elements in an array.

Some Parameters of the numpy.arcsin() function

  • x (array) – This parameter defines the input array of which the inverse sine values are to be found.
  • out (array, None, or tuple) – This parameter defines the location in which the result is stored. If this parameter is not defined then the result is returned in a new array.

There are many other parameters like where (array), casting, order, etc. Also, note that only the x (array) parameter is necessary to define. All the other parameters are optional.

Example:

import numpy as np
input_array = [-1, 0, 0.3, 0.6, 1]
print ("Input Array :", input_array)
arcsin_Values = np.arcsin(input_array)
print ("Inverse Sine values :", arcsin_Values)

Output:

Input Array : [-1, 0, 0.3, 0.6, 1] Inverse Sine values : [-1.57079633 0. 0.30469265 0.64350111 1.57079633]

Graphical Representation of the numpy.arcsin() function.

In this program, the Matplotlib library is used to plot the graph. This library is a very good library when it comes to data visualisation in python.

In the program below, the linspace() function of the NumPy is used. The linspace() function helps in creating a random numerical sequence that are evenly spaced.

import numpy as np
import matplotlib.pyplot as plt
input_array = np.linspace(-np.pi, np.pi, 15)
output_array = np.arcsin(input_array)
print("input_array :", input_array)
print("output_array with arcsin :", output_array)
plt.plot(input_array, output_array,color = 'red', marker = "o")
plt.title("numpy.arcsin()")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Output:

input_array : [-3.14159265 -2.6927937 -2.24399475 -1.7951958 -1.34639685 -0.8975979
-0.44879895 0. 0.44879895 0.8975979 1.34639685 1.7951958
2.24399475 2.6927937 3.14159265] output_array with arcsin : [ nan nan nan nan nan -1.11428969
-0.46542088 0. 0.46542088 1.11428969 nan nan
nan nan nan]

Use the math.asin() Function of the Math Library

Python’s Math library helps in performing complex mathematical problems by providing different mathematical constants and functions in Python.

The asin() function of the Math library is also used for calculating the inverse sine value (between -1 to 1) of a given input value in Python.

Example:

import math
print (math.asin(-1))
print (math.asin(0))
print (math.asin(0.3))
print (math.asin(0.6))
print (math.asin(1))

Output:

-1.5707963267948966
0.0
0.30469265401539747
0.6435011087932844
1.5707963267948966

Use the sympy.asin() Function of the SymPy Library

Python’s SymPy library is used in symbolic mathematics. It is a Computer Algebra System (CAS) that provides short and precise codes that can be used easily by the user.

The asin() function of the SymPy library is also used for calculating the inverse sine value of a given input value in Python.

Example:

from sympy import *
input_value = asin(1)
print(input_value)

Output:

pi/2

That’s all about how to get inverse sine in Python.

]]>
https://java2blog.com/inverse-sine-in-python/feed/ 0
Inverse Cosine in Python https://java2blog.com/inverse-cosine-python/?utm_source=rss&utm_medium=rss&utm_campaign=inverse-cosine-python https://java2blog.com/inverse-cosine-python/#respond Tue, 24 Aug 2021 14:12:04 +0000 https://java2blog.com/?p=16429 In Python, one can perform many kinds of tasks including mathematical operations like add, subtract, divide, dealing with matrices, etc. Besides all these operations, one can also perform complex mathematical operations like dealing with sets and matrices, trigonometric operations using many libraries and modules provided by Python.

In this tutorial, we will see how to find out the inverse cosine value in Python.

Use the numpy.arccos Function of the NumPy` Library to calculate the inverse cosine in Python.

The NumPy library is a widely used library in Python. This library helps in dealing with arrays, matrices, linear algebra, and Fourier transform. NumPy stands for Numerical Python.

The NumPy has a function known as the arccos() function that is a mathematical function used to calculate the inverse cosine of elements in an array.

Some Parameters of the numpy.arccos() function

  • x (array) – This parameter defines the input array of which the inverse sine values are to be found.
  • out (array, None, or tuple) – This parameter defines the location in which the result is stored. If this parameter is not defined then the result is returned in a new array.

There are many other parameters like where (array), casting, order, etc. Also, note that only the x (array) parameter is necessary to define. All the other parameters are optional.

Example:

import numpy as np
input_array = [-1, 0, 0.3, 0.6, 1]
print ("Input Array :", input_array)
arccos_Values = np.arccos(input_array)
print ("Inverse Cos values :", arccos_Values)

Output:

Input Array : [-1, 0, 0.3, 0.6, 1] Inverse Cos values : [3.14159265 1.57079633 1.26610367 0.92729522 0. ]

Graphical Representation of the numpy.arccos() function to calculate the inverse cosine in Python.

In this program, the Matplotlib library is used to plot the graph. This library is a very good library when it comes to data visualisation in python.

In the program below, the linspace() function of the NumPy is used. The linspace() function helps in creating a random numerical sequence that are evenly spaced.

import numpy as np
import matplotlib.pyplot as plt
input_array = np.linspace(-np.pi, np.pi, 15)
output_array = np.arccos(input_array)
print("input_array :", input_array)
print("output_array with arccos :", output_array)
plt.plot(input_array, output_array,color = 'red', marker = "o")
plt.title("numpy.arccos()")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Output:

input_array : [-3.14159265 -2.6927937 -2.24399475 -1.7951958 -1.34639685 -0.8975979
-0.44879895 0. 0.44879895 0.8975979 1.34639685 1.7951958
2.24399475 2.6927937 3.14159265] output_array with arccos : [ nan nan nan nan nan 2.68508602
2.0362172 1.57079633 1.10537545 0.45650663 nan nan
nan nan nan]

Use the math.acos() Function of the Math Library to calculate the inverse cos in Python.

Python’s Math library helps in performing complex mathematical problems by providing different mathematical constants and functions in Python.

The acos() function of the Math library is also used for calculating the inverse cosine value of a given input value in Python.

Example:

import math
print (math.acos(-1))
print (math.acos(0))
print (math.acos(0.3))
print (math.acos(0.6))
print (math.acos(1))

Output:

3.141592653589793
1.5707963267948966
1.266103672779499
0.9272952180016123
0.0

Use the sympy.acos() Function of the SymPy Library to calculate the inverse cosine in Python.

Python’s SymPy library is used in symbolic mathematics. It is a Computer Algebra System (CAS) that provides short and precise codes that can be used easily by the user.

The acos() function of the SymPy library is also used for calculating the inverse cosine value of a given input value in Python.

Example:

from sympy import *
input_value = acos(1)
print(input_value)

Output:

0

That’s all about how to get inverse cosine in Python.

]]>
https://java2blog.com/inverse-cosine-python/feed/ 0
Inverse Tangent in Python https://java2blog.com/inverse-tangent-python/?utm_source=rss&utm_medium=rss&utm_campaign=inverse-tangent-python https://java2blog.com/inverse-tangent-python/#respond Tue, 24 Aug 2021 14:04:21 +0000 https://java2blog.com/?p=16425 In Python, one can perform many kinds of tasks including mathematical operations like add, subtract, divide, dealing with matrices, etc. Besides all these operations, one can also perform complex mathematical operations like trigonometric operations using many libraries and modules provided by Python.

This tutorial will demonstrate how to calculate inverse tangent in Python.

Use the arctan() Function from the NumPy Library to calculate the inverse tangent in Python.

The NumPy library is a widely used library in Python. This library helps in dealing with arrays, matrices, linear algebra, and Fourier transform. NumPy stands for Numerical Python.

The NumPy has a function known as the arctan() function that is a mathematical function used to calculate the inverse tangent of elements in an array.

Some Parameters of the numpy.arctan() Function

  • x (array) – This parameter defines the input array of which the inverse sine values are to be found.
  • out (array, None, or tuple) – This parameter defines the location in which the result is stored. If this parameter is not defined then the result is returned in a new array.

There are many other parameters like where (array), casting, order, etc. Also, note that only the x (array) parameter is necessary to define. All the other parameters are optional.

Example:

import numpy as np
array = [-1, 0, 0.5, 1]
print ("Array: ", array)
arctan_Values = np.arctan(array)
print ("Inverse Tangent values of elements in the given Array : ",arctan_Values)

Output:

Array: [-1, 0, 0.5, 1] Inverse Tangent values of elements in the given Array : [-0.78539816 0. 0.46364761 0.78539816]

This function calculates the inverse tangent values of every element present in the input array.

Graphical Representation of the numpy.arctan() function.

In this program, the Matplotlib library is used to plot the graph. This library is a very good library when it comes to data visualisation in python.

In the program below, the linspace() function of the NumPy is used. The linspace() function helps in creating a random numerical sequence that are evenly spaced.

import numpy as np
import matplotlib.pyplot as plt
input_array = np.linspace(-np.pi, np.pi, 15)
output_array = np.arctan(input_array)
print("input_array :", input_array)
print("output_array with arctan :", output_array)
plt.plot(input_array, output_array,color = 'red', marker = "o")
plt.title("numpy.arctan()")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Output:

input_array : [-3.14159265 -2.6927937 -2.24399475 -1.7951958 -1.34639685 -0.8975979
-0.44879895 0. 0.44879895 0.8975979 1.34639685 1.7951958
2.24399475 2.6927937 3.14159265] output_array with arctan : [-1.26262726 -1.21521935 -1.15157923 -1.06256244 -0.93196875 -0.73148639
-0.42185468 0. 0.42185468 0.73148639 0.93196875 1.06256244
1.15157923 1.21521935 1.26262726]

Use the atan() Function from the SymPy Library to calculate the inverse tangent in Python.

Python’s SymPy library is used in symbolic mathematics. It is a Computer Algebra System (CAS) that provides short and precise codes that can be used easily by the user.

The atan() function of the SymPy library is used for calculating the inverse tangent value of a given input value in Python.

from sympy import *
inv_tan1 = atan(0)
inv_tan2 = atan(0.5)
print(inv_tan1)
print(inv_tan2)

Output:

0
0.463647609000806

Use the atan() Function from the Math Library to calculate the inverse tangent in Python.

Python’s Math library helps in performing complex mathematical problems by providing different mathematical constants and functions in Python.

The atan() function of the Math library is also used for calculating the inverse tangent value (between -PI/2 and PI/2) of a given input value in Python.

Example:

import math 
print (math.atan(0))
print (math.atan(0.5))

Output:

0.0
0.46364760900080615

That’s all about how to get inverse tangent in Python.

]]>
https://java2blog.com/inverse-tangent-python/feed/ 0