Меню

A float is required python ошибка

What is the problem?

By assigning to inputs to Value_1, separated by a comma, you are defining a tuple. As a short example for this:

In [1]: tup = 42, 23

In [2]: type(tup)
Out[2]: tuple

However, the math.sqrt function requires a float value as input, not a tuple.

How to solve this

You can use tuple unpacking to keep the structure of your original post intact:

import math

# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))

# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2

# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.

x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)

distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))

As you can see above it can be helpful to save the information for the point as a tuple first and then use the unpacked coordinates at at a different point.

I hope this sheds some light on what happened.

Уведомления

  • Начало
  • » Python для новичков
  • » Не могу исправить ошибку (Легкая программа)

#1 Сен. 26, 2016 16:04:48

Не могу исправить ошибку (Легкая программа)

 import math
a=float(input("Введіть число a: "))
x=float(input("Введіть число х: "))
y=(2/a*x)*(math.pow((math.tan),2/3))*(a*x/2)-(math.pow((math.tan),3))*(a*x/2)
print("Відповідь: ", format(y,'.2f'))
input()

выдаёт ошибку: TypeError: a float is required

Помогите!

Прикреплённый файлы:
attachment 0.png (1,2 KБ)

Офлайн

  • Пожаловаться

#2 Сен. 26, 2016 16:27:06

Не могу исправить ошибку (Легкая программа)

Return the tangent of x radians.

Другими словами

 (math.pow((math.tan),2/3))

— ошибка! Нужно указать тангенс чего

Влодение рускай арфаграфией — это как владение кунг-фу: настаящие мастира не преминяют ево бес ниабхадимости

Офлайн

  • Пожаловаться

#4 Сен. 26, 2016 20:18:09

Не могу исправить ошибку (Легкая программа)

A=Mas_dab1
C=Mas_dab2
Max=0.0 # отношение Ai/Ci
Max=A/C

Помогите, пожалуйста, не знаю как написать, что элементы массива С не могут быть равными 0.

Офлайн

  • Пожаловаться

#5 Сен. 27, 2016 08:19:15

Не могу исправить ошибку (Легкая программа)

Щас вот не понял…

Влодение рускай арфаграфией — это как владение кунг-фу: настаящие мастира не преминяют ево бес ниабхадимости

Офлайн

  • Пожаловаться

#6 Сен. 27, 2016 08:28:41

Не могу исправить ошибку (Легкая программа)

Anna_Keld
A=Mas_dab1C=Mas_dab2Max=0.0 # отношение Ai/CiMax=A/CПомогите, пожалуйста, не знаю как написать, что элементы массива С не могут быть равными 0.

 C = [1,2,3,0]
assert 0 not in C, "Houston, we've got a problem"

Офлайн

  • Пожаловаться

#7 Сен. 28, 2016 17:24:44

Не могу исправить ошибку (Легкая программа)

Подскажите, пожалуйста, по проблеме.

 from datetime import datetime
past = input('')
now = datetime.now()
print(past)
print(datetime.now())
age = datetime.now() - datetime(past)
print(age)
print(age.days/365)

1980, 1, 1
1980, 1, 1
2016-09-28 17:22:06.219872
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-8-eeea22692c41> in <module>()
4 print(past)
5 print(datetime.now())
—-> 6 age = datetime.now() — datetime(past)
7 print(age)
8 print(age.days/365)

TypeError: an integer is required (got type str)

Пробовал так

 age = datetime.now() - str(datetime(past))
age = str(datetime.now() - datetime(past))

Отредактировано gyddik (Сен. 28, 2016 17:26:46)

Офлайн

  • Пожаловаться

#8 Сен. 29, 2016 02:23:23

Не могу исправить ошибку (Легкая программа)

gyddik
datetime в вашем коде не принимает строку, которую вы ввели с клавиатуры, для этого смотрите в строну datetime.strftime

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

Офлайн

  • Пожаловаться

#9 Сен. 29, 2016 11:50:56

Не могу исправить ошибку (Легкая программа)

JOHN_16
gyddikdatetime в вашем коде не принимает строку, которую вы ввели с клавиатуры, для этого смотрите в строну datetime.strftime

Спасибо, но все равно не догоняю.

 from datetime import datetime
a = input()
b = datetime.strptime(a, '%Y%m%d')
c = datetime.now()
now = c.strftime('%Y, %m, %d')
past = b.strftime('%Y, %m, %d')
print(past)
print(now)
age = datetime(now) - datetime(past)
print(age)
print(age.days/365)

555599
5555, 09, 09
2016, 09, 29
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-31-69f67edee1e1> in <module>()
7 print(past)
8 print(now)
—-> 9 age = datetime(now) — datetime(past)
10 print(age)
11 print(age.days/365)

TypeError: an integer is required (got type str)

Офлайн

  • Пожаловаться

#10 Сен. 29, 2016 17:27:49

Не могу исправить ошибку (Легкая программа)

Разобрался
Вот, что получилось:

 from datetime import datetime, date, time
a = input()
born = datetime.strptime(a, "%Y, %m, %d")
now = datetime.now()
age = born - now
print(age)
print(age.days/365)

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Не могу исправить ошибку (Легкая программа)
TypeError: Must Be Real Number, Not STR

The TypeError: must be real number, not str error involves using a wrong type and a non-real number, and in this case, an str type.

Working with datatypes can be tricky, but it is important to enforce or ensure you are parsing the right data type to a function to avoid such TypeError.

This article will explain how the TypeError: must be real number, not str error occurs in the first place and how to solve it using type conversion.

Use float() or int() to Solve TypeError: must be real number, not str in Python

When working with functions, especially built-in functions, the arguments required are often of a particular type. It could be any of the primitive data types, int, float, string, or Boolean.

Therefore, it is important to make sure that the values we are working with and parsing are of the right data.

A typical example is working with the built-in input() function to take a number and work with the number in a simple mathematical expression.

number = input("Enter a Number: ")
print(number/34 + 45 * number)

Output:

Enter a Number: 12
Traceback (most recent call last):
  File "C:UsersakinlDocumentsPythonsteps.py", line 2, in <module>
    print(number/34 + 45 * number)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Here, we have a TypeError message because the number binding held a string data 12; instead of an integer or float number, 12.

However, this TypeError: unsupported operand type(s) for /: 'str' and 'int' is different from this TypeError: must be real number, not str error. The distinction is in the operation that’s happening.

Let’s use the math library in Python to round down the number that the user inputs.

import math
number = input("Enter a Number: ")
print(math.floor(number))

Output:

Enter a Number: 12.45
Traceback (most recent call last):
  File "C:UsersakinlDocumentsPythonsteps.py", line 3, in <module>
    print(math.floor(number))
TypeError: must be real number, not str

Now, the TypeError is different because we are parsing the number binding, which contains a string to the floor() method, and the method requires a number, float or integer.

Therefore, to solve the problem, we need to convert the datatype of the value the user passes to the number binding to float or integer, depending on what we need.

The built-in float() function is most appropriate when dealing with floating point numbers. Given that we need decimal numbers to round up, we need the float() function.

import math
number = float(input("Enter a Number: "))
print(math.floor(number))

Output:

Enter a Number: 123.45
123

The int() function can be useful for cases where the number needed is a whole number. If we only need whole numbers to be parsed to the sin() method, we can use the int() method.

import math
number = int(input("Enter a Number: "))
print(math.sin(number))

Output:

Enter a Number: 12
-0.5365729180004349

It can be easier to solve for simpler cases but trickier for some complex or harder scenarios. For example, it might be hard to see where you need to convert if you are working on a randomized trigonometric calculator.

It is always better to convert immediately, especially before the operation expression. In this case, the mathematical operation.

import random, math

def create():
    global sideA
    sideA = format(random.uniform(1, 100), '.0f')
    global sideB
    sideB = format(random.uniform(1, 100), '.0f')
    global angleA
    angleA = format(random.uniform(1, 180), ',.3f')
    global angleB
    angleB = ANGLE_B()

    return angleB

def ANGLE_B():
    angle = format(math.asin(sideB*(math.sin(angleA)/sideA)), '.3f')
    return angle

print(create())

Output:

Traceback (most recent call last):
  File "c:UsersakinlDocumentsPythonfloat.py", line 18, in <module>
    print(create())
  File "c:UsersakinlDocumentsPythonfloat.py", line 11, in create
    angle_b = ANGLE_B()
  File "c:UsersakinlDocumentsPythonfloat.py", line 15, in ANGLE_B
    ang = format(math.asin(side_b*(math.sin(angle_a)/side_a)), '.3f')
TypeError: must be real number, not str

If you trace the error you can see it starts from print(create()) which calls the ANGLE_B() function uses the binding sideA, sideB, and angleA.

These bindings are parsed to the math methods, which require float and int data values. However, the binding’s datatype is strings and needs to be converted to either float or int.

In this case, the more responsible way to solve the code issue is to convert the datatype before use in mathematical expression since we don’t need to change the value again.

import random, math

def create():
    global sideA
    sideA = float(format(random.uniform(1, 100), '.0f'))
    global sideB
    sideB = float(format(random.uniform(1, 100), '.0f'))
    global angleA
    angleA = float(format(random.uniform(1, 180), ',.3f'))
    global angleB
    angleB = ANGLE_B()

    return angleB

def ANGLE_B():
    angle = math.asin(sideB*(math.sin(angleA)/sideA))
    return angle

print(create())

Output:

Therefore, be defensive when dealing with datatypes, and make sure that after working with the date, convert the data to the necessary datatype.

Newbie here. I’m following a (Python, Flask, MySQL) tutorial and am getting a «TypeError: a float is required» error when running some example code.

Tutorial: https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Python3_Flask.html#zz-6.2
Code: http://pastebin.com/1jwCE8Y8
Error:

Traceback (most recent call last):
  File "sqlalchemy_app2.py", line 82, in <module>
    print(instance)     # Invoke __repr__()
  File "sqlalchemy_app2.py", line 40, in __repr__
    self.id, self.category, self.name, self.price)
TypeError: a float is required

Here’s what I’ve tried:

One:
[line 27] Changing price = Column(Numeric(precision=5,scale=2)) to price = Column(Float(precision=5,scale=2))
NameError: name ‘Float’ is not defined

Two:
[line 39] Changing return "<Cafe(%d, %s, %s, %5.2f)>" % ( to return "<Cafe(%d, %s, %s, %d)>" % (
TypeError: %d format: a number is required, not NoneType

Three:
[line 39] Changing return "<Cafe(%d, %s, %s, %5.2f)>" % ( to return "<Cafe(%d, %s, %s, %f)>" % (
TypeError: a float is required

How do I update my code so that I no longer get the «TypeError: a float is required» error? I’m using Python3. Thanks in advance.

Edit to include I’m using SQLAlchemy

catboost version: 0.16.4
Operating System: Windows 10 64-bits
CPU: Intel Core i7 8th Gen
Python 2.7
Problem:

When I try to fit a simple CatBoostClassifier on my DataFrame containing categorical variables, I get the very cryptic error below.

Here is what I did to try to troubleshoot down the issue:

  • tested a clean notebook on a tutorial (https://github.com/catboost/tutorials/blob/master/python_tutorial.ipynb) —> OK
  • fit CatBoostClassifier only on my non-categorical variables —> OK
  • try to encode with a LabelEncoder my categorical variables and then fit CatBoostClassifier —> OK
  • try to use any single categorical variable without encoding like in the titanic tutorial above —> KO

I can’t understand what’s happening here and have no idea on how to debug this further. If anyone has any idea, please let me know, I can provide more info.

Here is the code failing (it’s not a minimal example, I’m not sure how I can reproduce this):

import catboost
model = catboost.CatBoostClassifier(custom_loss=['Accuracy'], random_seed=0, eval_metric='AUC', logging_level='Silent')
model.fit(X_train.loc[:, ['categoricalvariable']], y_train_enc,
    cat_features=[0],
    plot=True
)

And the error traceback:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-7e62575dc820> in <module>()
----> 5     plot=True
      6 )

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in fit(self, X, y, cat_features, sample_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
   3455         self._fit(X, y, cat_features, None, sample_weight, None, None, None, None, baseline, use_best_model,
   3456                   eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period,
-> 3457                   silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
   3458         return self
   3459 

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _fit(self, X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
   1386             use_best_model, eval_set, verbose, logging_level, plot,
   1387             column_description, verbose_eval, metric_period, silent, early_stopping_rounds,
-> 1388             save_snapshot, snapshot_file, snapshot_interval, init_model
   1389         )
   1390         params = train_params["params"]

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _prepare_train_params(self, X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model)
   1281             del params['cat_features']
   1282 
-> 1283         train_pool = _build_train_pool(X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, column_description)
   1284         if train_pool.is_empty_:
   1285             raise CatBoostError("X is empty.")

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _build_train_pool(X, y, cat_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, column_description)
    697             raise CatBoostError("y has not initialized in fit(): X is not catboost.Pool object, y must be not None in fit().")
    698         train_pool = Pool(X, y, cat_features=cat_features, pairs=pairs, weight=sample_weight, group_id=group_id,
--> 699                           group_weight=group_weight, subgroup_id=subgroup_id, pairs_weight=pairs_weight, baseline=baseline)
    700     return train_pool
    701 

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in __init__(self, data, label, cat_features, column_description, pairs, delimiter, has_header, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names, thread_count)
    326                         )
    327 
--> 328                 self._init(data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
    329         super(Pool, self).__init__()
    330 

C:UsersAIAnaconda2libsite-packagescatboostcore.pyc in _init(self, data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
    678             baseline = np.reshape(baseline, (samples_count, -1))
    679             self._check_baseline_shape(baseline, samples_count)
--> 680         self._init_pool(data, label, cat_features, pairs, weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, feature_names)
    681 
    682 

_catboost.pyx in _catboost._PoolBase._init_pool()

_catboost.pyx in _catboost._PoolBase._init_pool()

_catboost.pyx in _catboost._PoolBase._init_features_order_layout_pool()

_catboost.pyx in _catboost._set_features_order_data_pd_data_frame()

_catboost.pyx in _catboost.get_cat_factor_bytes_representation()

_catboost.pyx in _catboost.get_id_object_bytes_string_representation()

TypeError: a float is required

I have a python script with some parameters — see screen.
enter image description here

You see the last parameter is of type Double, default Value 0.

The code i have this:

Ausrichtung = float(arcpy.GetParameterAsText(9))
if Ausrichtung == '#' or not Ausrichtung:
    Ausrichtung = "0.0"
# maybe there is some useless ballast...it comes from an export from modelbuilder, and I am learning python now.

arcpy.AddMessage("Ausrichtung"+ Ausrichtung)
SteigungX = -math.sin(math.radians(Ausrichtung))

1) When I start the script — in the form i let for this parameter a 0, i always get:
Ausrichtung0.0
TypeError: a float is required
2) If I start the schript — with this parameter as a 5, it works.
3) When I replace last line with
SteigungX = -math.sin(math.radians(float(Ausrichtung)))
it works with all values, also with 0

I have several more parameters before this, and I can calculate with them.

Why is Zero so different?

Why do I have Ausrichtung in case 1) a 0, even when I use this float function?

AddMessage give a 0.0, so why still not recognized as float?

Математическая библиотека в Python предоставляет нам доступ к некоторым общим математическим функциям и константам, которые мы можем использовать в нашем коде для более сложных математических вычислений.

Библиотека является встроенным модулем Python, поэтому вам не нужно выполнять установку, чтобы использовать ее. В этой статье мы покажем пример использования наиболее часто используемых функций и констант математической библиотеки Python.

Специальные константы

Математическая библиотека в Python содержит две важные константы.

Pie

Первая – это Pie (π), очень популярная математическая константа. Он обозначает отношение длины окружности к диаметру круга и имеет значение 3,141592653589793. Чтобы получить к нему доступ, мы сначала импортируем математическую библиотеку следующим образом:

import math

Затем мы можем получить доступ к этой константе с помощью pi:

math.pi

Вывод:

3.141592653589793

Вы можете использовать эту константу для вычисления площади или длины окружности. Следующий пример демонстрирует это:

import math

radius = 2
print('The area of a circle with a radius of 2 is:', math.pi * (radius ** 2))

Вывод:

The area of a circle with a radius of 2 is: 12.566370614359172

Мы увеличили значение радиуса до степени 2, а затем умножили его на круговую диаграмму в соответствии с формулой площади πr 2 .

Число Эйлера

Число Эйлера (e), являющееся основанием натурального логарифма, также определено в библиотеке Math. Мы можем получить к нему доступ следующим образом:

math.e

Вывод:

2.718281828459045

В следующем примере показано, как использовать указанную выше константу:

import math

print((math.e + 6 / 2) * 4.32)

Вывод:

24.702977498943074

Показатели и логарифмы

В этом разделе мы рассмотрим функции библиотеки Math, используемые для поиска различных типов показателей и логарифмов.

Функция exp()

Математическая библиотека в Python поставляется с функцией exp(), которую мы можем использовать для вычисления степени e. Например, e x , что означает экспоненту от x. Значение e составляет 2,718281828459045.

Метод можно использовать со следующим синтаксисом:

math.exp(x)

Параметр x может быть положительным или отрицательным числом. Если x не является числом, метод вернет ошибку. Продемонстрируем использование этого метода на примере:

import math

# Initializing values
an_int = 6
a_neg_int = -8
a_float = 2.00

# Pass the values to exp() method and print
print(math.exp(an_int))
print(math.exp(a_neg_int))
print(math.exp(a_float))

Вывод:

403.4287934927351
0.00033546262790251185
7.38905609893065

Мы объявили три переменные и присвоили им значения с разными числовыми типами данных. Затем мы передали их методу exp() для вычисления их показателей.

Мы также можем применить этот метод к встроенным константам, как показано ниже:

import math

print(math.exp(math.e))
print(math.exp(math.pi))

Вывод:

15.154262241479262
23.140692632779267

Если вы передадите методу нечисловое значение, он выдаст ошибку, как показано здесь:

import math

print(math.exp("20"))

Вывод:

Traceback (most recent call last):
  File "C:/Users/admin/mathe.py", line 3, in <module>
    print (math.exp("20"))
TypeError: a float is required

Ошибка TypeError была сгенерирована, как показано в приведенных выше выходных данных.

Функция log()

Эта функция возвращает логарифм указанного числа. Натуральный логарифм вычисляется по основанию e. Следующий пример демонстрирует использование этой функции:

import math

print("math.log(10.43):", math.log(10.43))
print("math.log(20):", math.log(20))
print("math.log(math.pi):", math.log(math.pi))

В приведенном выше скрипте мы передали методу числовые значения с разными типами данных. Мы также вычислили натуральный логарифм константы пи. Результат выглядит так:

Вывод:

math.log(10.43): 2.344686269012681
math.log(20): 2.995732273553991
math.log(math.pi): 1.1447298858494002

Функция log10()

Этот метод возвращает десятичный логарифм указанного числа. Например:

import math

# Returns the log10 of 50
print("The log10 of 50 is:", math.log10(50))

Вывод:

The log10 of 50 is: 1.6989700043360187

Функция log2()

Эта функция вычисляет логарифм числа по основанию 2. Например:

import math

# Returns the log2 of 16
print("The log2 of 16 is:", math.log2(16))

Вывод:

The log2 of 16 is: 4.0

Функция log (x, y)

Эта функция возвращает логарифм x, где y является основанием. Например:

import math

# Returns the log of 3,4
print("The log 3 with base 4 is:", math.log(3, 4))

Вывод:

The log 3 with base 4 is: 0.6309297535714574

Функция log1p (x)

Эта функция вычисляет логарифм (1 + x), как показано здесь:

import math

print("Logarithm(1+x) value of 10 is:", math.log1p(10))

Вывод:

Logarithm(1+x) value of 10 is: 2.3978952727983707

Арифметические функции

Арифметические функции используются для представления чисел в различных формах и выполнения над ними математических операций. Некоторые из наиболее распространенных арифметических функций обсуждаются ниже:

  • ceil(): возвращает максимальное значение указанного числа.
  • fabs(): возвращает абсолютное значение указанного числа.
  • floor(): возвращает минимальное значение указанного числа.
  • gcd (a, b): возвращает наибольший общий делитель a и b.
  • fsum (iterable): возвращает сумму всех элементов в повторяемом объекте.
  • expm1(): возвращает (e ^ x) -1.
  • exp (x) -1: когда значение x мало, вычисление exp (x) -1 может привести к значительной потере точности. Expm1 (x) может возвращать результат с полной точностью.

Следующий пример демонстрирует использование вышеуказанных функций:

import math

num = -4.28
a = 14
b = 8
num_list = [10, 8.25, 75, 7.04, -86.23, -6.43, 8.4]
x = 1e-4 # A small value of x

print('The number is:', num)
print('The floor value is:', math.floor(num))
print('The ceiling value is:', math.ceil(num))
print('The absolute value is:', math.fabs(num))
print('The GCD of a and b is: ' + str(math.gcd(a, b)))
print('Sum of the list elements is: ' + str(math.fsum(num_list)))
print('e^x (using function exp()) is:', math.exp(x)-1)
print('e^x (using function expml()) is:', math.expm1(x))

Вывод:

The number is: -4.28
The floor value is: -5
The ceiling value is: -4
The absolute value is: 4.28
The GCD of a and b is: 2
Sum of the list elements is: 16.029999999999998
e^x (using function exp()) is: 0.0001000050001667141
e^x (using function expml()) is: 0.00010000500016667084

К другим математическим функциям относятся следующие:

  • pow(): принимает два аргумента с плавающей запятой, переводит первый аргумент во второй и возвращает результат. Например, pow (2,2) эквивалентно 2 ** 2.
  • sqrt(): возвращает квадратный корень указанного числа.

Эти методы можно использовать, как показано ниже:

math.pow(3, 4)

Вывод:

81.0

Квадратный корень:

math.sqrt(81)

Вывод:

9.0

Тригонометрические функции

Модуль Math в Python поддерживает все тригонометрические функции. Некоторые из них перечислены ниже:

  • sin (a): возвращает синус буквы “a” в радианах.
  • cos (a): возвращает косинус “a” в радианах.
  • tan (a): возвращает тангенс буквы a в радианах.
  • asin (a): возвращает значение, обратное синусу. Также есть «атан» и «акос».
  • degrees (а): преобразует угол «а» из радиан в градусы.
  • radians (а): преобразует угол «а» из градусов в радианы.

Рассмотрим следующий пример:

import math

angle_In_Degrees = 62
angle_In_Radians = math.radians(angle_In_Degrees)

print('The value of the angle is:', angle_In_Radians)
print('sin(x) is:', math.sin(angle_In_Radians))
print('tan(x) is:', math.tan(angle_In_Radians))
print('cos(x) is:', math.cos(angle_In_Radians))

Вывод:

The value of the angle is: 1.0821041362364843
sin(x) is: 0.8829475928589269
tan(x) is: 1.8807264653463318
cos(x) is: 0.46947156278589086

Обратите внимание, что мы сначала преобразовали значение угла из градусов в радианы перед выполнением других операций.

Преобразование типов

Вы можете преобразовать число из одного типа в другой. Этот процесс известен, как «принуждение». Python может внутренне преобразовывать число из одного типа в другой, если выражение имеет значения смешанных типов. Следующий пример демонстрирует это:

3 + 5.1

Вывод:

8.1

В приведенном выше примере целое число 3 было приведено к значению 3,0 (число с плавающей запятой) для операции сложения, и результатом также является число с плавающей запятой.

Однако иногда вам необходимо явно привести число от одного типа к другому, чтобы удовлетворить требованиям параметра функции или оператора. Это можно сделать с помощью различных встроенных функций Python. Например, чтобы преобразовать целое число в число с плавающей запятой, мы должны вызвать функцию float(), как показано ниже:

a = 12
b = float(a)
print(b)

Вывод:

12.0

Целое число преобразовано в число с плавающей запятой. Число с плавающей запятой можно преобразовать в целое число следующим образом:

a = 12.65
b = int(a)
print(b)

Вывод:

12

Число с плавающей запятой было преобразовано в целое путем удаления дробной части и сохранения основного числа. Обратите внимание, что когда вы конвертируете значение в int таким образом, оно будет усечено, а не округлено.

Заключение

Математическая библиотека в Python предоставляет нам функции и константы, которые мы можем использовать для выполнения арифметических и тригонометрических операций.

Библиотека устанавливается на Python, поэтому вам не требуется выполнять дополнительную установку, чтобы использовать ее. Для получения дополнительной информации вы можете найти здесь официальную документацию.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Add windowscapability сбой add windowscapability код ошибки 0x80072ee6
  • Altistart 48 ошибки php