Runtimeerror: expected scalar type long but found float

The Runtimeerror: expected scalar type long but found float error is a type error which occurs when you attempt to perform an operation that requires an integer (a scalar type long) on a floating-point number (a scalar type float).

In other words, you’re attempting to use a floating-point number where an integer is anticipated.

How to Reproduce the Error?

The following example below will show on how to reproduce an error.

import torch

# Define a tensor with float data type
float_tensor = torch.tensor([1.0, 2.0, 3.0])

# Try to perform an operation that requires a long data type
long_tensor = torch.zeros(3, dtype=torch.long)
result = long_tensor + float_tensor

In this example, we first define a tensor float_tensor with a data type of float. We then attempt to perform an operation where we add float_tensor to a tensor of zeros long_tensor, which has a data type of long.

This operation will result:

RuntimeError: expected scalar type long but found float

Next, Let’s take a look at some possible common causes of this error.

What are the Common Causes of the error?

There are multiple reasons why you might encounter this error. Here are some possible common causes:

  • Using a floating-point number where an integer is expected
  • Mixing integer and floating-point values in an operation
  • Using the wrong data type for a function argument

How to Fix the Expected Scalar Type Long But Found Float Error?

Now that we understand what causes this error let’s discuss some solutions on how to fix it.

Solution 1: Convert the floating-point number to an integer

The easiest solution to fix this error is to convert the floating-point number to an integer using the int() function.

For example:

x = 3.5
y = int(x)
print(y)

In this example, the int() function converts the floating-point number 3.5 to an integer.

Then, the output will be:

C:\Users\Joken\Documents\RuntimeError\Scripts\python.exe C:/Users/Joken/PycharmProjects/pythonProject6/main.py
3

Solution 2: Use the correct data type in an operation

The next solution to solve this error is to use the correct data type in an operation. If you’re performing an operation that requires an integer.

Make sure you’re using an integer and not a floating-point number.

For example, instead of using 3.5 in an operation, use 3.

x = 10
y = 3.5
result = x // y
print(result)

In this example, we’re using the floating-point number 3.5 as the divisor in the division operation.

When we run this code, we’ll get a TypeError because the // operator expects an integer.

To fix this, we can use the correct data type in the operation.

Here’s an example code:

x = 10
y = 3
result = x // y
print(result)

In this example, we’re using the integer 3 as the divisor in the division operation.

When we run this code, we’ll get the expected result, which is the integer quotient of 3.

By using the correct data type in the operation, we can avoid errors and unexpected results in our code.

Solution 3: Check the data types of function arguments

Then, another solution to solve this error is to Check the data types of function arguments.

If you’re passing arguments to a function, make sure you’re using the correct data type for each argument.

If you’re passing a floating-point number where an integer is expected, convert it to an integer before passing it to the function.

For Example:

def multiply_numbers(x, y):
    return x * y

x = 10
y = 4.5
if isinstance(x, int) and isinstance(y, int):
    result = multiply_numbers(x, y)
    print(result)
else:
    print("Error: Invalid input types.")

In this example, we’re first checking if x and y are both integers using the isinstance() function.

Then, If both x and y are integers, we call the multiply_numbers function with these arguments and print the result. If either x or y is not an integer, we print an error message instead.

Solution 4: Use floor division instead of regular division

The solution to solve this error is to use floor division instead of regular division.

if you’re dividing two integers and want an integer result, use floor division (//) instead of regular division (/).

Here’s the example code using regular division:

x = 7
y = 2
result = x / y
print(result)

In this example, we’re dividing x by y using regular division (/). When we run this code, we’ll get a float result (3.5), which is not what we want.

To fix this, we can use floor division (//) instead:

x = 7
y = 2
result = x // y
print(result)

In this example, we’re using floor division (//) to divide x by y. If we run this code, we’ll get an integer result (3), which is what we want.

By using floor division instead of regular division, we can ensure that we get an integer result when dividing two integers.

Solution 5: Use the dtype parameter when creating NumPy arrays

The solution to solve this error is to Use the dtype parameter when creating NumPy arrays.

If you’re creating a NumPy array, make sure to specify the data type using the dtype parameter.

For example:

import numpy as np

x = np.array([1.5, 2.5, 3.5], dtype=int)

In this example, we’re creating a NumPy array of floating-point numbers and specifying that we want them to be converted to integers using the dtype=int parameter.

Solution 6: Use the astype() method to convert data types in NumPy arrays

To solve this error is to use the astype() method to convert data types in NumPy.

If you already have a NumPy array and need to convert the data type, you can use the astype() method.

For example:

import numpy as np

x = np.array([1.5, 2.5, 3.5])
y = x.astype(int)

In this example, we’re converting the floating-point numbers in the x array to integers using the astype() method.

Solution 7: Convert the input tensor to double using the double() function

To solve this error Runtimeerror: expected scalar type long but found float we need to convert the input tensor to double using the double() function.

For example:

import torch
import torch.nn as nn

class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.linear = nn.Linear(10, 1)

def forward(self, x):
return self.linear(x)

model = SimpleModel().double()
new_input_tensor = torch.randn(10, 10, dtype=torch.float)


new_input_tensor = new_input_tensor.double()

output = model(new_input_tensor)
print(output)

In this example, the new input tensor is also converted to a double data type using the .double() method. The model is then run on the new input tensor, and the output is printed.

tensor([[ 0.3043],
[-0.2060],
[ 0.9363],
[-0.3219],
[ 0.1011],
[-0.2654],
[ 0.1723],
[ 0.1856],
[-0.2681],
[ 0.0259]], dtype=torch.float64, grad_fn=)

Solution 8: Convert the model to float to fix the error

The last solution to solve the error is to convert the model to float to fix the error.

For example:

import torch
import torch.nn as nn

class SimpleModel(nn.Module):
  def __init__(self):
    super(SimpleModel, self).__init__()
    self.linear = nn.Linear(10, 1)

  def forward(self, x):
    return self.linear(x)

# Convert the model to float
my_model = SimpleModel().to(torch.float)
input_tensor = torch.randn(5, 10, dtype=torch.float)

output = my_model(input_tensor)
print(output)

The model is then converted to a float type and a random input tensor with dimensions (5, 10) is created. The input tensor is passed through the model to compute the output, which is then printed to the console.

Output:

tensor([[-0.2566],
[ 0.3341],
[ 1.2688],
[-1.1049],
[-0.2115]], grad_fn=)

Additional Resources

Conclusion

In conclusion, if you encounter this error, you need to check if you’re using a floating-point number where an integer is expected or mixing integer and floating-point values in an operation.

If you are, use one of the solutions we’ve outlined in this article to fix the error. By doing that, you can make sure that your Python code runs smoothly without any errors.

We hope you found this article helpful in fixing the “Runtimeerror expected scalar type long but found float” error.

FAQs

Why do I get the “Runtimeerror expected scalar type long but found float” error?

You get this error when you try to use a floating-point number where an integer is expected or mix integer and floating-point values in an operation.

What is a scalar data type?

A scalar data type refers to a single value, such as an integer, floating-point number, or boolean value.

What causes the “RuntimeError expected scalar type long but found float” error message?

The error message occurs when a function or operation expects a long integer data type but instead receives a float data type.