@@ -15,7 +15,7 @@ const SCALE_FACTOR: u64 = 10_000; // 10^4 for 4 decimal places
1515const SCALE_FACTOR_F64 : f64 = SCALE_FACTOR as f64 ;
1616
1717/// Convert a floating-point value to a field element using fixed-point arithmetic
18- fn quantize_to_field < F : PrimeField > ( value : f64 ) -> F {
18+ fn quantize_to_field < F : PrimeField + Field > ( value : f64 ) -> F {
1919 // Handle special cases
2020 if value == 0.0 {
2121 return F :: zero ( ) ;
@@ -43,7 +43,7 @@ fn quantize_to_field<F: PrimeField>(value: f64) -> F {
4343}
4444
4545/// Convert a field element back to a floating-point value
46- fn dequantize_from_field < F : PrimeField > ( value : F ) -> f64 {
46+ fn dequantize_from_field < F : PrimeField + Field > ( value : F ) -> f64 {
4747 // Handle special cases
4848 if value == F :: zero ( ) {
4949 return 0.0 ;
@@ -56,9 +56,11 @@ fn dequantize_from_field<F: PrimeField>(value: F) -> f64 {
5656 }
5757
5858 // Convert to bytes and then to u64
59- let bytes = value. to_repr ( ) ;
59+ let bytes = value. to_repr ( ) . as_ref ( ) ;
6060 let mut u64_bytes = [ 0u8 ; 8 ] ;
61- u64_bytes. copy_from_slice ( & bytes[ 0 ..8 ] ) ;
61+ if bytes. len ( ) >= 8 {
62+ u64_bytes. copy_from_slice ( & bytes[ ..8 ] ) ;
63+ }
6264 let scaled = u64:: from_le_bytes ( u64_bytes) ;
6365
6466 // Dequantize by dividing by scale factor
@@ -252,6 +254,24 @@ mod tests {
252254 assert_eq ! ( dequantize_from_field( neg_one_field) , -1.0 ) ;
253255 }
254256
257+ #[ test]
258+ fn test_large_field_values ( ) {
259+ // Test values close to u64::MAX to verify byte representation handling
260+ let large_value = ( u64:: MAX >> 1 ) as f64 / SCALE_FACTOR_F64 ;
261+ let field_val: Fp = quantize_to_field ( large_value) ;
262+ let roundtrip = dequantize_from_field ( field_val) ;
263+ let epsilon = 1e-4 ;
264+ assert ! ( ( large_value - roundtrip) . abs( ) < epsilon,
265+ "Large value roundtrip failed for {}: got {}" , large_value, roundtrip) ;
266+
267+ // Test values requiring full field representation
268+ let max_safe_value = ( ( 1u64 << 53 ) - 1 ) as f64 / SCALE_FACTOR_F64 ;
269+ let field_val: Fp = quantize_to_field ( max_safe_value) ;
270+ let roundtrip = dequantize_from_field ( field_val) ;
271+ assert ! ( ( max_safe_value - roundtrip) . abs( ) < epsilon,
272+ "Max safe value roundtrip failed for {}: got {}" , max_safe_value, roundtrip) ;
273+ }
274+
255275 #[ test]
256276 fn test_proof_generation_and_verification ( ) {
257277 Python :: with_gil ( |py| {
0 commit comments