All Questions
Tagged with floating-point python-3.x
72
questions with no upvoted or accepted answers
4votes
0answers
357views
Convert List of Floating point to bytearray and back in Python
I am trying to convert a list of floating point number to bytearray and convert it back to original list. My list looks like this:
[-0.055999, -0.054000, -0.049, -0.040999, -0.037000]
I am trying to ...
4votes
2answers
187views
Create a program that returns the smallest cube which exceeds a non-negative integer n
So I'm trying to create a program which generates the smallest cube greater than an integer n.
def first_cube_above(n):
#Return the smallest cube which exceeds the non-negative integer n.
...
2votes
1answer
253views
Stochastically rounding a float to an integer
I want a function (using Python 3.6+ if it's relevant) that will stochastically round a floating-point number to an integer in the following manner:
Given a real number, x, let a = floor(x) and let b ...
2votes
1answer
318views
How do you convert data from float64 to int16 in python 3?
Currently I am using soundfile to read audio data from a wav file like so:
import soundfile
raw_data, sample_rate = soundfile.read(filename)
Whilst I realise that you can select dtype=int16, I would ...
2votes
0answers
831views
Convert Exponential values into float number on the fly in python
I am trying to show decimal values instead of exponential values as it is required for end user.
You can see the code below,
currentValue1='1.56e-65'
print("%f" % float(currentValue1))
print(float(...
1vote
0answers
20views
How to catch a floating point error after fpectl has been removed?
Python 3.8.12 removed the fpectl module.
This module enabled catching floating point errors as standard Python exceptions.
I have a Python programme which uses a module which, in turns, calls a closed-...
1vote
1answer
38views
Getting different values for Decimal LocalContext Type
I have written following code to determine type of decimal localcontext:
print('decimal.localcontext() type: ', type(decimal.localcontext()))
Output:
decimal.localcontext() type: <class 'decimal....
1vote
1answer
40views
How to get first 4 digits after the 0s in a decimal but keeping 0s • Python
I need the first 4 digits after the front 0s in a decimal while also keeping the 0s in the output without getting scientific notation.
Would like to take
0.0000000000000000000000634546534
and get
0....
1vote
1answer
67views
How does Python convert floats to strings internally?
In part of Python's documentation, there is a part that says:
Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers ...
1vote
0answers
229views
How can I convert XYZ point cloud to binary mask image
I want to convert a set of point cloud (X, Y, Z) to a binary mask image using python. The problem is that these points are float and out of range of 0-255. To more specific, the points are related to ...
1vote
0answers
39views
Benchmarking Float Precision per Operation in Numpy
I want to benchmark the error between 64-bit floats and 32 bit floats in Numpy for addition and multiplication. Unfortunately, I could not find exactly what I was looking for when searching for the ...
1vote
0answers
31views
Different output on Function on assesment (Hackerrank) (FIXED)
So, for this assessment on Hackerrank i need to calculate the ratios on given input. So i coded but whenever iam running this on my own shell it gives me the right output ,but in the compiler from ...
1vote
0answers
83views
How do I set the default decimal number separator in Python?
I am working on two applications, one running in C#/.NET and the other with the Python 3 interpreter targeting Windows 10 only. The two applications communicate with each other using a local network ...
1vote
1answer
146views
Floating-point arithmetic - bits of the exponent
I have a general question about floating-point arithmetic.
Recently, I got quite interested in understanding of the computing in programmes, thus I started to solve exercises. I would like you to ...
1vote
0answers
437views
Can I use Python's Decimal type with NumPy?
I'm doing some calculations with Python3 and NumPy using float64 and sometimes, when I change my formulas a little (but mathematically equivalent), then I get slightly different results. I know that ...
1vote
1answer
68views
Python2 like behaviour in Python3
I am running a Jupyter Notebook, running Python3 on a Macbook (OS X Sierra). The only recent change I have made is to install Jupyter Notebook Extensions. Now I get Python 2.x like division instead of ...
1vote
0answers
93views
Inconsistent Python Calculations
I am writing a function to calculate the chi-squared statistic of a piece of ciphertext to determine the most likely key for a caesar cipher.
To calculate the chi-squared statistic I calculate the ...
1vote
1answer
43views
python hack converting floats to decimals
I've written a large program, with dependencies on libraries written in my lab. I'm getting wrong (and somewhat random) results, which are caused by floating-point errors.
I would like to do some ...
1vote
2answers
2kviews
Only accept a float between 0 and 1 - python
So I need a really efficient code which will accept any number between 0 and 1 from the user and keep on prompting them to try again until their input meets this criteria.
This is what I've got so far:...
0votes
0answers
14views
subclass for NameError: name 'side_length' is not defined
class Polygon():
def __init__(self, side_lengths):
self.side_lengths = side_lengths
def perimeter(self):
return sum(self.side_lengths)
def __str__(self):
side_lengths = len(self....
0votes
0answers
24views
How to calculate change in coins in python
I was given a prompt that asks to input any amount of money and print how many of each coin is needed for that amount of money. For example, 2.05 would be 8 quarters and 1 nickel. I thought I had it ...
0votes
0answers
25views
df.to_csv adds extra decimal to a object type column
I am trying to write a dataframe to csv using df.to_csv.
I read the data using read_excel and all columns are read as dtype=object.
df = pf.read_excl(f, dtype=str)
df.head()
df.to_csv(new_file )
...
0votes
1answer
22views
Unable to populate column in dataframe using value from dict which is present in dict inside list in one of the column
I have one column in data frame with values like this List with dictionary inside
[{'symbol': '$', 'value': 5.2, 'currency': 'USD', 'raw': '$5.20', 'name': '$5.20$5.20 ($1.30/Fl Oz)', 'asin': '...
0votes
0answers
52views
Inconsistent results with floating point arithmetic (color conversion formulae)
I am trying to parse a bunch of color values from various files, perform lightness changes, and write them back into the files. I have to put this in a PKGBUILD for the Arch User Repository and would ...
0votes
0answers
22views
numpy seterrcall, how to flag the object that caused the flouting point error?
I have a function that loops through a list of objects, each these objects are associated with numpy functions (add, multiple, divide).
When calling the object with arguments, the associated numpy ...
0votes
1answer
96views
Manually calculating IEEE-754 floating point fractions and splitting up the bits - Python
I'm trying to come up with a way to do this:
Lets say the fraction portion of my IEEE-754 floating point number is 0b10110011001100110011010
I'm trying to take each bit and multiply it by a power of 2 ...
0votes
1answer
50views
How to accurately determine if an mpfr number is an integer or not in gmpy2?
I am trying to write a program that converts radian n (actually any int or float) to degree minute second representation and back, as a simple programming exercise.
The output should be like this: d°m'...
0votes
1answer
494views
ValueError: could not convert string to float: '86,5484466552734'
When changing to a float using
final.iloc[:,4:10]=final.iloc[:,4:10].replace(',', '.').astype(float)
I am getting the following error:
[ValueError Traceback (most ...
0votes
0answers
138views
Python 3 - ValueError: could not convert string to float: '-'
so i am reading data from xlsx file, all values are float when i check with "features.dtypes", but getting this error: AttributeError: 'Series' object has no attribute 'reshape'
xl = pd....
0votes
2answers
46views
Python3 Determine if logarithm is "perfect," i.e., no remainder on float
Problem statement:
I am trying to determine if a logarithm is "perfect," i.e., there is no remainder. The issue I am having is that math.log() always returns a float.
I read this: https://...
0votes
1answer
39views
changing rounding mode via importing libm in python 3
My environment: Ubuntu 18.04, Anaconda, Python 3.6
I am using following code to import libm in python via ctypes in order to change floating type environment such as rounding.
import numpy as np
...
0votes
2answers
36views
How do I write a code for matrix using users input without numpy in python?
---Without using numpy---
I have to write a code where at i am receiving input from user, n, which is the number of rows of my matrix (integer). afterwards - I will be receiving from the user n rows ...
0votes
0answers
108views
Modifying the preexisting float class in python to include a custom round function
I'm new to Python and I am having problems with floating point arithmetic. From what I understand, floating point arithmetic in Python generates binary approximations of decimal values and we deal ...
0votes
2answers
77views
The decimal.Decimal() function is producing an unrounded result
I am new to Python and I am having trouble with the Decimal function in the decimal module in Python. I understand that due to the way that Python stores float values in memory, in order to perform ...
0votes
1answer
403views
csv importing latitude column as float need it to be numeric
After importing a csv file, i plot it using streamlit.
The issue is that the column type imported for the lat/long is are float. How do I transform this float into a readable format?
I have tried a ...
0votes
2answers
90views
Implement a function that turns floats into fractions from scratch without external modules
I was given a task to find a way to make a function to turn floats into fractions as accurate as possible,
and by sheer brute forcing, i created a function like this
def isclose(a, b, tolerance):
...
0votes
0answers
49views
How to predict the output without a computer?
Consider the following python code.
s = 0.0
for i in range(10):
s += 0.1
print(s == 1.0)
Will the output of the above be true ?
This was a past paper question of a python written exam paper. I know ...
0votes
0answers
43views
python floor division floats
According to pep238 the semantics of floor division is
a // b == floor(a / b)
However this fails with floats:
>>> 1.99965 // 0.0199965
99.0
>>> math.floor(1.99965 / 0.0199965)
100
...
0votes
1answer
111views
Python 3.8 issue - print of float with 5 digits after dot - error in PyCharm?
I am using PyCharm, Python version is 3.8
I receive the below error once I try to print e.g. 5 digits after dot for float sum variable being 3.14+2.17:
print(f'{test:.5f}')
^
...
0votes
0answers
94views
Best practices to avoid Python float rounding errors?
So I encountered my first noticeable issue with float representation in Python.
The error came from multiplying the float:2.55 by the float:100. The error being I expect 255.0, but python returns 254....
0votes
0answers
42views
How to convert commas to dot in Python
I have a text file containing some data with 3 columns as below, how can I convert them to dots (float) in Python 3.5? Thank you in advance !
2,723 331,288 2,981592
2,701 331,208 2,980872
10,...
0votes
2answers
159views
Trying to calculate the average of a float list?
I don't know if I'm going about getting the floatvalues the right way but this is what I have so far.
grades_file = open('grades.txt', 'r')
# Print Header & spacer
print('Name' + '\t\tGrade')
...
0votes
1answer
91views
Return True/False for a matched or an unmatched floating point number using Regex in Python
I need to print (True) for all the matched floating-point numbers in the user-defined input and (False) if the input is not a Floating point number.
I have so far come up with this:
import re
...
0votes
0answers
57views
How do i convert a str to a float?
Input:
df.groupby('Age Group').size()
Output:
18 thru 24 352
25 thru 34 358
35 thru 44 341
45 thru 54 336
55 and Older 269
Under 18 103
dtype: int64
...
0votes
0answers
173views
Python float conversion from incomplete Fortran sci-notation
The problem
I am producing data files with Fortran 90 program and then analyzing it with Python 3.7. The data files are just many numbers, written in scientific notation.
My problem is that at some ...
0votes
1answer
200views
Variable return types of DecimalField
I have a model thats something like this:
class Item(models.Model):
value_a = models.DecimalField(default=0.0, decimal_places=4, max_digits=20)
value_b = models.DecimalField(default=0.0, ...
0votes
1answer
34views
Float number cannot read context from discord?
Trying to make a calculator for my website for website currency, the problem is it has floating value it said TypeError: float() argument must be a string or a number, not 'Context'
Making the ...
0votes
2answers
45views
Consistent Type Error regarding converting a string to a float in Python
I am working on an assignment for an Introduction to Programming course and would like some direction as to what I am missing and why I continue getting the same TypeError. I am able to assign my ...
0votes
0answers
103views
Floating-point inaccuracies in Python - how to fix
I'm writing a program that calculates the expected value of the sum of two discrete random variables. Here is the code:
EX = 0
EY = 0
X_number=int(input("Enter the number of possible values for X: ")...
0votes
2answers
529views
Float is not converting to integer pandas
I used this code to convert my float numbers into an integer, however, it does not work. Here are all step I gone through so far:
Step 1: I converted timestamp1 and timestamp2 to datetime in order ...