[ EN | PT] Perl - Math | Perl - Matemática

in HiveDevs2 years ago

Banner

Read too on Odysee

One of the most important things in any programming language is its support for mathematical operations. With Perl it's no different: the language supports most of the mathematical operations you'll need in your academic and professional life, and I'm going to comment on the most basic ones here, so you'll be able to go on your own.

Perl supports several numeric data types. Below are some usage examples:

10 # integer
-10 # negative integer
123.45 # floating point (float)
6.2E2 # scientific notation
0xffff # hexadecimal (starting with "0x")
0377 # octal (starts with "0")
0b100111101 # binary (starts with "0b")
5_232_999_435 # large numbers arranged with underscores

Internally, however, it works as if all numbers are floating point. That is, 1 becomes 1.0, 2 becomes 2.0, and so on.

Perl also supports different math functions such as addition, subtraction, multiplication, division, exponentiation and remainder of division. Let's see what each of them does.

Addition, as the name implies, is about adding two numbers to form a third. The mathematical expression 23 + 32, for example, returns 55. We also have to keep in mind that negative numbers can also be added, but the effect of this addition will be the same as a subtraction of a positive integer, that is, the expression 32 + (-23) will result in 9. See the examples below:

print 23 + 32, "\n"; # 55
print 32 + (-23), "\n"; # 9

Now the subtraction. Subtraction is about doing the inverse operation of division, that is, if 23 + 32 = 55, then 55 - 32 = 23. The same rule of negative number prevails, that is, if the number is negative, the function will be changed, so 9 - (-23) = 32. Check out the examples below:

print 55 - 32, "\n"; # 23
print 9 - (-23), "\n"; # 32

Multiplication would be the same as a process of consecutive additions, that is, 2 * 3 is the same thing as 2 + 2 + 2, or 3 + 3. In this case, having a negative number in the operation will only make the final result negative (i.e. 2 * -2 = -4), while having two negative numbers will make the result positive (i.e. -2 * -2 = 4). Look at the examples below:

print 2 * 3, "\n"; # 6
print 2 * -3, "\n"; # -6
print -2 * -3, "\n"; # 6

The division is something a little more complex. Dividing one number by another would be finding which number that multiplied by the divisor would give the number that was divided (yes, the concept is confusing, but I'll give you examples). Think of the following: 4 / 2 = 2 because 2 * 2 = 4, 8 / 2 = 4 because 4 * 2 = 8, and so on.

However, in this case, there is a small difference. What if we try to do 2 / 4? The result in this case will be 0.5, a floating point number, and 0.5 * 4 = 2. Look at the examples:

print 4 / 2, "\n"; # 2
print 2 / 4, "\n"; # 0.5
print 8 / 2, "\n"; # 4

But what about the rest of the division? To know this, we will have to understand the concept of integer division. In computing mathematics, there are two types of division: conventional, floating-point, and integer, which deals only with integers. That is, while in a conventional division, 2 / 4 = 0.5, in an integer division it would be 2 / 4 = 0. Okay, but what about the rest of the division? Simple, as the operation of taking the remainder of the division in Perl is defined by the character %, the final operation will look like this: 2 % 4 = 2.

This type of operation is used, for example, to check whether a number is even or odd: if the remainder of the division of a number by 2 is 0, the number is even, otherwise, it is odd. See some examples:

print 4 % 2, "\n"; # 0
print 4 % 3, "\n"; # 1
print 2 % 5, "\n"; # 2
print 3 % 2, "\n"; # 1
print 3 % 5, "\n"; # 3

print 4 % 2 == 0 ? "true" : "false", "\n"; # true
print 3 % 2 == 0 ? "true" : "false", "\n"; # false
print 2 % 2 == 0 ? "true" : "false", "\n"; # true
print 0 % 2 == 0 ? "true" : "false", "\n"; # true
print 50 % 2 == 0 ? "true" : "false", "\n"; # true

Potentiation (identified by ** in Perl) is about multiplying a number by itself x times, i.e. 2 ** 2 is the same thing as 2 * 2, and 2 ** 3 is the same as 2 * 2 * 2. See some examples below:

print 2 ** 2, "\n"; # 4
print 5 ** 2, "\n"; # 25
print 2 ** 3, "\n"; # 8
print 2.5 ** 2, "\n"; # 6.25
print 0.5 ** 5, "\n"; # 0.03125

Now that we have examples of numbers, how about trying some math operations? Let's start with the simplest. Try running the following formulas, and see your results:

  • 4 ** 3
  • 5 + 4 + 3 + 2 -1
  • 2 / 4
  • 3 * 25
  • 5 % 3

Now let's learn a little about precedence of operations. What is the result of 1 + 2 * 3? For some it might be 9, because they will first calculate 1 + 2 (which will give 3), and then 3 * 3, which will give 9, while for others the result will be 7, because they will first calculate 2 * 3, which will give 6, and then 1 + 6, which will give 7. But what is the correct way? Let's try using Perl. Run the following command in your shell:

perl -e 'print 1 + 2 * 3, "\n";'

The result was 7, and this is because of operator precedence. Precedence in Perl (and most languages) follows the following order of precedence:

order of precedencesymboldescription
1()Content inside parentheses
2++ --Unary operators
3**Potentiation
4* / %Mathematical operators for multiplication, division and remainder of division
5+ -Addition and Subtraction Operators
6< <= > >=Comparative Operators
7== !=Comparative Equality Operators
8= += -= *= /= **=Assignment Operators

Traders you don't know, don't worry: you'll learn in the next tutorials.

And then? Was there any doubt? Do you have any criticism, praise or comment? Leave it below, your opinion is very important to me 😄☺️

References


Banner

Leia também na Odysee

Uma das coisas mais importantes em qualquer linguagem de programação é seu suporte a operações matemáticas. Com Perl não é diferente: a linguagem oferece suporte a maioria das operações matemáticas que você vai precisar em sua vida acadêmica e profissional, e eu vou comentar aqui as mais básicas, para que você seja capaz de seguir com as próprias pernas.

O Perl dá suporte a diversos tipos de dados numéricos. Abaixo, alguns exemplos de uso:

10 # inteiro
-10 # inteiro negativo
123.45 # ponto flutuante (float)
6.2E2 # notação científica
0xffff # hexadecimal (iniciados com "0x")
0377 # octal (começa com "0")
0b100111101 # binário (começa com "0b")
5_232_999_435 # números grandes organizados com underline

Internamente, no entanto, ele trabalha como se todos os números fossem de ponto flutuante. Ou seja, 1 vira 1.0, 2 vira 2.0, e assim por diante.

O Perl também tem suporte a diferentes funções matemáticas, como soma, subtração, multiplicação, divisão, exponenciação e resto da divisão. Vejamos o que cada um deles faz.

A adição, como o próprio nome diz, se trata de você somar dois números para formar um terceiro. A expressão matemática 23 + 32, por exemplo, tem como resultado 55. Também temos que ter em mente que números negativos também podem ser somados, mas o efeito dessa soma será o mesmo de uma subtração de um inteiro positivo, ou seja, a expressão 32 + (-23) terá como resultado 9. Observe abaixo os exemplos:

print 23 + 32, "\n"; # 55
print 32 + (-23), "\n"; # 9

Agora a subtração. A subtração se trata de fazer a operação inversa da divisão, ou seja, se 23 + 32 = 55, então 55 - 32 = 23. A mesma regra do número negativo prevalece, ou seja, se o número for negativo, a função vai ser alterada, logo, 9 - (-23) = 32. Confira os exemplos abaixo:

print 55 - 32, "\n"; # 23
print 9 - (-23), "\n"; # 32

A multiplicação seria o mesmo que um processo de somas consecutivas, ou seja, 2 * 3 é a mesma coisa que 2 + 2 + 2, ou que 3 + 3. Nesse caso, ter um número negativo na operação só fará que o resultado final seja negativo (ou seja, 2 * -2 = -4), enquanto ter dois números negativos fará o resultado ficar positivo (ou seja, -2 * -2 = 4). Observe os exemplos abaixo:

print 2 * 3, "\n"; # 6
print 2 * -3, "\n"; # -6
print -2 * -3, "\n"; # 6

A divisão é algo um pouco mais complexo. Dividir um número por outro seria encontrar qual número que multiplicado pelo divisor daria o número que foi dividido (sim, o conceito é confuso, mas já vou te dar exemplos). Pense no seguinte: 4 / 2 = 2 porque 2 * 2 = 4, 8 / 2 = 4 porque 4 * 2 = 8, e assim por diante.

Porém, nesse caso, existe uma pequena diferença. E se tentarmos fazer 2 / 4? O resultado, nesse caso, será 0.5, um número de ponto flutuante, e 0.5 * 4 = 2. Olhe os exemplos:

print 4 / 2, "\n"; # 2
print 2 / 4, "\n"; # 0.5
print 8 / 2, "\n"; # 4

Mas e o que é o resto da divisão? Para sabermos isso, teremos que entender o conceito de divisão inteira. Na matemática para computação, existem dois tipos de divisão: a convencional, de ponto flutuante, e a inteira, que trata apenas de números inteiros. Ou seja, enquanto em uma divisão convencional, 2 / 4 = 0.5, em uma divisão inteira seria 2 / 4 = 0. Ok, mas e o resto da divisão? Simples, como a operação de pegar o resto da divisão, em Perl, é definida pelo caractere %, a operação final ficará assim: 2 % 4 = 2.

Esse tipo de operação é usado, por exemplo, para verificar se um número é par ou impar: se o resto da divisão de um número por 2 for 0, o número é par, senão, é ímpar. Veja alguns exemplos:

print 4 % 2, "\n"; # 0
print 4 % 3, "\n"; # 1
print 2 % 5, "\n"; # 2
print 3 % 2, "\n"; # 1
print 3 % 5, "\n"; # 3

print 4 % 2 == 0 ? "true" : "false", "\n"; # true
print 3 % 2 == 0 ? "true" : "false", "\n"; # false
print 2 % 2 == 0 ? "true" : "false", "\n"; # true
print 0 % 2 == 0 ? "true" : "false", "\n"; # true
print 50 % 2 == 0 ? "true" : "false", "\n"; # true

Potenciação (identificada por ** em Perl) se trata de multiplicar um número por ele mesmo x vezes, ou seja, 2 ** 2 é a mesma coisa que 2 * 2, e 2 ** 3 é o mesmo que 2 * 2 * 2. Veja alguns exemplos abaixo:

print 2 ** 2, "\n"; # 4
print 5 ** 2, "\n"; # 25
print 2 ** 3, "\n"; # 8
print 2.5 ** 2, "\n"; # 6.25
print 0.5 ** 5, "\n"; # 0.03125

Agora que temos exemplos de números, que tal tentar algumas operações matemáticas? Vamos começar pelo mais simples. Tente rodar as seguintes fórmulas, e veja seus resultados:

  • 4 ** 3
  • 5 + 4 + 3 + 2 -1
  • 2 / 4
  • 3 * 25
  • 5 % 3

Agora vamos aprender um pouco sobre precedência de operações. Qual o resultado de 1 + 2 * 3? Para alguns, pode ser 9, porque vão calcular primeiro 1 + 2 (que vai dar 3), e depois 3 * 3, que vai dar 9, enquanto para outros o resultado vai ser 7, porque vão calcular primeiro 2 * 3, que vai dar 6, e depois 1 + 6, que vai dar 7. Mas qual é a forma correta? Vamos tentar usando Perl. Rode o seguinte comando no seu shell:

perl -e 'print 1 + 2 * 3, "\n";'

O resultado foi 7, e isso é por causa da precedência de operadores. A precedência em Perl (e na maioria das linguagens) segue a seguinte ordem de precedência:

ordem de precedênciasímbolodescrição
1()Conteúdo dentro de parênteses
2++ --Operadores unários
3**Potenciação
4* / %Operadores matemáticos de multiplicação, divisão e resto da divisão
5+ -Operadores de adição e subtração
6< <= > >=Operadores comparativos
7== !=Operadores comparativos de igualdade
8= += -= *= /= **=Operadores de atribuição

Os operadores que você não conhece, não se preocupe: você aprenderá nos próximos tutoriais.

E então? Ficou alguma dúvida? Tem alguma crítica, elogio ou comentário? Deixa aí embaixo, sua opinião é muito importante para mim 😄☺️

Material de referência

Sort:  

Yay! 🤗
Your content has been boosted with Ecency Points, by @arthursiq5.
Use Ecency daily to boost your growth on platform!

Support Ecency
Vote for new Proposal
Delegate HP and earn more

!HBIT

Success! You mined 1.0 HBIT on Wusang: Isle of Blaq. | tools | wallet | discord | community | daily <><

And, you found a Blaq gold coin (BLAQGOLD)!



Check your bonus treasure tokens by entering your username at an H-E explorer or take a look at your wallet.

Read about Hivebits (HBIT) or read the story of Wusang: Isle of Blaq.

Obrigado por ter compartlhado essa postagem na Comunidade Brasil.

Metade das recompensas dessa resposta serão destinadas ao autor do post.

!HBIT

Success! You mined 1.0 HBIT on Wusang: Isle of Blaq. Sorry, but you didn't find a bonus treasure token today. Try again tomorrow...they're out there! | tools | wallet | discord | community | daily <><

Check for bonus treasure tokens by entering your username at an H-E explorer or take a look at your wallet.

Read about Hivebits (HBIT) or read the story of Wusang: Isle of Blaq.