M
Modular15mo ago
Corgo

Type suffixing?

I was curious if there was a builtin way to define the types of decimal constants. For instance, in Java I can specify the constant as a float by adding an F to the end:
float mult = .6F*.91F;
float acceleration = 0.16277136F / (mult * mult * mult);

System.out.println(acceleration);
float mult = .6F*.91F;
float acceleration = 0.16277136F / (mult * mult * mult);

System.out.println(acceleration);
In Python, I can use numpy to define the type but it's much more annoying to write:
from numpy import float32
mult = float32(.6)*float32(.91)
acceleration = float32(0.16277136) / (mult * mult * mult)

print(acceleration)
from numpy import float32
mult = float32(.6)*float32(.91)
acceleration = float32(0.16277136) / (mult * mult * mult)

print(acceleration)
Since Mojo adds typing, I was curious if there's a way I can do it similar to Java or without having to use numpy. To elaborate a bit, the following code produces a different output than my Java and Python examples (which produce the same):
fn main():
let mult: Float32 = 0.6*0.91
let acceleration: Float32 = 0.16277136 / (mult * mult * mult)
print(acceleration)
fn main():
let mult: Float32 = 0.6*0.91
let acceleration: Float32 = 0.16277136 / (mult * mult * mult)
print(acceleration)
5 Replies
roopesh puthalath
@Corgo fn main() raises: let mult: Float32 = FloatLiteral(0.6) *FloatLiteral(0.91) let acceleration: Float32 = FloatLiteral(0.16277136) / (mult * mult * mult) print(acceleration) 1.0000002384185791
Corgo
CorgoOP15mo ago
yes, the other two print 0.9999998 which is what i'm looking for FloatLiteral() casts it to a 64-bit float, whereas i need them to be 32-bit floats
roopesh puthalath
from math import mul from math import div fn main() raises: let mult: Float32 = FloatLiteral(0.6) *FloatLiteral(0.91) let k =mult * mult * mult let acceleration: Float32 = FloatLiteral(0.16277136) / k print("accel",acceleration) let multVector1 = SIMDDType.float32, 1 let multVector2 = SIMDDType.float32, 1 let multResult = mul[DType.float32, 1](multVector1, multVector2) let squareResult = mul[DType.float32, 1](multResult, multResult) let cubeResult = mul[DType.float32, 1](multResult, squareResult) let accelerationNumerator = SIMDDType.float32, 1 let accelerationVector = div[DType.float32, 1](accelerationNumerator, cubeResult) print(accelerationVector ) @Corgo Could you please try this 0.99999982118606567 @Corgo the accelerationVector print should give you expected value
Corgo
CorgoOP15mo ago
realized i can just do this
fn f(x: Float32) -> Float32:
return x

fn main():
let mult: Float32 = f(.6)*f(.91)
let acceleration: Float32 = f(0.16277136) / (mult * mult * mult)

print(acceleration)
fn f(x: Float32) -> Float32:
return x

fn main():
let mult: Float32 = f(.6)*f(.91)
let acceleration: Float32 = f(0.16277136) / (mult * mult * mult)

print(acceleration)
Want results from more Discord servers?
Add your server